udp函数:
头文件: #include #include
int sendto(int sockfd, const void *msg,int len,unsigned int flags,const struct sockaddr *to, int tolen);
该函数比send()函数多了两个参数,to表示目地机的IP地址和端口号信息,而tolen常常被赋值为sizeof (struct sockaddr)。Sendto 函数也返回实际发送的数据字节长度或在出现发送错误时返回-1。
Recvfrom()函数原型为:
int recvfrom(int sockfd,void *buf,int len,unsigned int flags,struct sockaddr *from,int *fromlen);
from是一个struct sockaddr类型的变量,该变量保存源机的IP地址及端口号。fromlen常置为sizeof(struct sockaddr)。当recvfrom()返回时,fromlen包含实际存入from中的数据字节数。Recvfrom()函数返回接收到的字节数或当出现错误时返回-1,并置相应的errno。
以下为服务端程序:
#include
#include
#include
#include
#include
#include
#include
#include
#include
int port = 8888;
int main()
{
int sockfd;
int len;
int z;
char buf[256];
struct sockaddr_in adr_inet;
struct sockaddr_in adr_clnt;
printf("wait client.....\n");
adr_inet.sin_family = AF_INET;
adr_inet.sin_port = htons(port);
adr_inet.sin_addr.s_addr = htonl(INADDR_ANY);
bzero(&(adr_inet.sin_zero), 8);
len = sizeof(adr_clnt);
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd == -1)
{
perror("create socket error");
exit(1);
}
z = bind(sockfd, (struct sockaddr *)&adr_inet, sizeof(adr_inet));
if (z == -1)
{
perror("bind error");
exit(1);
}
while (1)
{
z = recvfrom(sockfd, buf, sizeof(buf), 0, (struct sockaddr *)&adr_clnt, &len);
if (z < 0)
{
perror("recvfrom error");
exit(1);
}
buf[z] = '\0';
printf("receive: %s", buf);
if (strncmp(buf, "stop", 4) == 0)
{
printf("end........\n");
break;
}
}
close(sockfd);
exit(0);
}
以下为客户端程序:
#include
#include
#include
#include
#include
#include
#include
#include
#include
int port = 8888;
int main()
{
int sockfd;
int i = 0;
int z;
char buf[80], str1[80];
struct sockaddr_in adr_srvr;
FILE *fp;
printf("open file......\n");
fp = fopen("liu", "r");
if (fp == NULL)
{
perror("open file error");
exit(1);
}
printf("connect serve.....\n");
adr_srvr.sin_family = AF_INET;
adr_srvr.sin_port = htons(port);
adr_srvr.sin_addr.s_addr = htonl(INADDR_ANY);
bzero(&(adr_srvr.sin_zero), 8);
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd == -1)
{
perror("socket error");
exit(1);
}
printf("send file.....\n");
for (i = 0; i < 3; i++)
{
fgets(str1, 80, fp);
printf("%d: %s", i, str1);
sprintf(buf, "%d: %s", i, str1);
z = sendto(sockfd, buf, sizeof(buf), 0, (struct sockaddr *)&adr_srvr, \
sizeof(adr_srvr));
if (z < 0)
{
perror("sendto error");
exit(1);
}
}
printf("send ........\n");
sprintf(buf, "stop\n");
z = sendto(sockfd, buf, sizeof(buf), 0, (struct sockaddr *)&adr_srvr, sizeof(adr_srvr));
if (z < 0)
{
perror("send error");
exit(1);
}
fclose(fp);
close(sockfd);
exit(0);
}
建立文件liu
打开一个终端:运行服务程序
[root@localhost net]# ./udp_s
wait client.....
打开另一个终端,运行客户端程序
[root@localhost net]# ./udp_c
open file......
connect serve.....
send file.....
0: hello linux
1: hello world
2: nice to me you
send ........
[root@localhost net]#
服务端显示:
[root@localhost net]# ./udp_s
wait client.....
receive: 0: hello linux
receive: 1: hello world
receive: 2: nice to me you
receive: stop
end........
[root@localhost net]#
阅读(1766) | 评论(0) | 转发(0) |