遇到一个问题,本机IP修改之后,UDP收不到包了。走查代码发现socket绑定时填写的IP不是INADDR_ANY,而是绑成了固定IP,并且修改IP时没有重新绑socket。
为了验证这种情况,专门写了个程序验证。(只有一台linux,只能用win32写)
接受端:
- // winsock.cpp : Defines the entry point for the console application.
- //
- #include "stdafx.h"
- #include <Winsock2.h>
- int main(int argc, char* argv[])
- {
- SOCKET sock1;
- WSADATA wdate;
- struct sockaddr_in localaddr;
- struct sockaddr_in destaddr;
- int count;
- int len;
- char buff[1024];
- char ip[16];
- if(WSAStartup(MAKEWORD(2,1), &wdate))
- {
- printf("error in %s:%d.\n", __FILE__, __LINE__);
- WSACleanup();
- return 1;
- }
- printf("WSA初始化成功.\n");
- memset((void*)ip, 0, sizeof(ip));
- printf("输入本机IP:");
- scanf("%s", ip);
- len = sizeof(destaddr);
- localaddr.sin_family=AF_INET;
- localaddr.sin_port=htons(27015); ///监听端口
- localaddr.sin_addr.s_addr=inet_addr(ip); ///注意!此处绑定固定IP
- sock1 = socket(AF_INET, SOCK_DGRAM, 0);
- bind(sock1, (struct sockaddr *)&localaddr, sizeof(localaddr));
- count = 0;
- printf("waiting dgram....\n");
- while(1)
- {
- memset((void *)buff, 0, sizeof(buff));
- if(recvfrom(sock1, buff, sizeof(buff), 0, (struct sockaddr*)&destaddr, &len) == SOCKET_ERROR)
- {
- printf("error in %s:%d.\n", __FILE__, __LINE__);
- closesocket(sock1);
- WSACleanup();
- return 1;
- }
- count++;
- printf("recv from%s:%s\n", inet_ntoa(destaddr.sin_addr), buff);
- if(count > 100)
- break;
- }
- closesocket(sock1);
- WSACleanup();
- return 0;
- }
发送端:
- // winsocksender.cpp : Defines the entry point for the console application.
- //
- #include "stdafx.h"
- #include
- int main(int argc, char* argv[])
- {
- SOCKET sock1;
- WSADATA wdate;
- struct sockaddr_in localaddr;
- struct sockaddr_in destaddr;
- int count;
- int len;
- char ip[16];
- char buff[1024];
- if(WSAStartup(MAKEWORD(2,1), &wdate))
- {
- printf("error in %s:%d.\n", __FILE__, __LINE__);
- WSACleanup();
- return 1;
- }
- printf("WSA初始化成功.\n");
- printf("输入对端主机IP:");
- scanf("%s", ip);
- len = sizeof(destaddr);
- destaddr.sin_family=AF_INET;
- destaddr.sin_port=htons(27015); ///对端监听端口
- destaddr.sin_addr.s_addr=inet_addr(ip); ///对端IP
- sock1 = socket(AF_INET, SOCK_DGRAM, 0);
- //bind(sock1, (struct sockaddr *)&localaddr, sizeof(localaddr));
- count = 1;
- printf("start sending dgram....\n", count);
- while(1)
- {
- memset((void *)buff, 0, sizeof(buff));
- sprintf(buff, "dgram %d from sender.\n", count);
- if(sendto(sock1, buff, sizeof(buff), 0, (struct sockaddr*)&destaddr, len) == SOCKET_ERROR)
- {
- printf("error in %s:%d.\n", __FILE__, __LINE__);
- closesocket(sock1);
- WSACleanup();
- return 1;
- }
- printf("dgram %d have sent.\n", count);
- Sleep(10000);
- count++;
- if(count > 100)
- break;
- }
- closesocket(sock1);
- WSACleanup();
- return 0;
- }
实验:
1、打开接收端,输入本机IP,等待收包。
2、打开发送端,输入目的IP,开始发送。
此时接收端可以正常收包。
3、修改接收端 IP地址。
4、重启发送端,输入新的目的IP地址,开始发送。
此时接收端不能收包。
5、重启接收端,输入新IP,等待收包。
此时接受正常。
阅读(8838) | 评论(0) | 转发(0) |