UDP|UDP connect

【UDP|UDP connect】在UDP客户端和服务端的例子中,客户端代码如下:

#include #include #include #include #include #include #include void test( int sd, struct sockaddr_in *addr, int len) { char buf[4]; int ret; /* ret = connect(sd, (struct sockaddr *)addr, len); printf("connect ret = %d\n",ret); if(ret<0) perror("connect"); */ ret = sendto(sd, buf, 4, 0, (struct sockaddr *)addr, len); if(ret < 0) perror("first sendto"); /* ret = sendto(sd, buf, 4, 0, (struct sockaddr *)addr, len); if(ret < 0) perror("second sendto"); */ ret = recvfrom(sd, buf, 4, 0, (struct sockaddr *)addr,&len); if(ret < 0) perror("recvfrom "); }int main(int argc, char **argv) { int sd; struct sockaddr_in addr; bzero(&addr, sizeof(struct sockaddr_in)); addr.sin_family = AF_INET; addr.sin_port = htons(12345); inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr); sd = socket(AF_INET, SOCK_DGRAM, 0); test(sd, &addr, sizeof(addr)); return 0; }

  1. 调用connect sendto后会收到icmp消息,之后进行的任何sendto or recvfrom 均会显示connect refused
  2. 不掉用conncet, sendto 后会收到icmp消息,但是之后recvfrom会阻塞,sendto会继续产生icmp

    推荐阅读