UDP调用connect函数

来源:互联网 发布:微信一键转发程序源码 编辑:程序博客网 时间:2024/06/05 14:48

              UDP是无连接的,在发送数据时需要指定对端的IP地址和端口,每次发送数据需要重新连接(多次发数据导致效率低下),而且异步错误不会返回到UDP套接字。这些在UDP调用connect函数之后都发生了改变。代码如下:

服务端:

#include <unistd.h>#include <sys/types.h>#include <sys/socket.h>#include <netdb.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <ctype.h>#include <errno.h>#include <malloc.h>#include <netinet/in.h>#include <arpa/inet.h>#include <sys/ioctl.h>#include <stdarg.h>#include <fcntl.h>#include <sys/types.h>#include <sys/wait.h>#include <netinet/in.h>#include <arpa/inet.h>#include <signal.h>#define MAXLINE 4096int main(int argc ,char *argv[]){    int sockfd,loop=1,ret;    struct sockaddr_in seraddr;    bzero(&seraddr,sizeof(seraddr));    seraddr.sin_family=AF_INET;    seraddr.sin_port=htons(8888);    seraddr.sin_addr.s_addr=INADDR_ANY;    sockfd=socket(AF_INET,SOCK_DGRAM,0);    bind(sockfd,(sockaddr *)&seraddr,sizeof(seraddr));    socklen_t len=sizeof(sockaddr);    char buf[100]={0};    recv(sockfd,buf,strlen(buf)-1,0);    printf("buf=%s\n",buf);    close(sockfd);}
客户端:

#include <unistd.h>#include <sys/types.h>#include <sys/socket.h>#include <netdb.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <ctype.h>#include <errno.h>#include <malloc.h>#include <netinet/in.h>#include <arpa/inet.h>#include <sys/ioctl.h>#include <stdarg.h>#include <fcntl.h>#include <sys/types.h>#include <sys/wait.h>#include <netinet/in.h>#include <arpa/inet.h>#include <signal.h>#define MAXLINE 4096int main(){   int sockfd;   struct sockaddr_in seraddr;   sockfd=socket(AF_INET,SOCK_DGRAM,0);   bzero(&seraddr,sizeof(seraddr));   seraddr.sin_family=AF_INET;   seraddr.sin_addr.s_addr=inet_addr("127.0.0.1");   seraddr.sin_port=htons(8888);   connect(sockfd,(struct sockaddr *)&seraddr,sizeof(seraddr));   char buf[100]="123";   send(sockfd,buf,sizeof(buf)+1,0);   getchar();   exit(0);}

编译并运行,你会发现服务端有了打印。但是我们使用的是send和recv函数。

[mapan@localhost UDP]$ ./server buf=123
至于UDP调用connect函数之后异步错误的返回,我这里不演示了。






原创粉丝点击