日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

UDP调用connect函数

發布時間:2025/6/15 39 豆豆
生活随笔 收集整理的這篇文章主要介紹了 UDP调用connect函数 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

? ? ? ? ? ? ? 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函數之后異步錯誤的返回,我這里不演示了。

?

?

?

?

?

?

?

總結

以上是生活随笔為你收集整理的UDP调用connect函数的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。