开发平台(Platform): (Ex: VC++, GCC, Linux, ...)
Windows VC++
Linux GCC
问题(Question):
能否建立一UDP连线, 可以接收指定IP的封包
我尝试Windows的写法, 也试过Linux的写法, 但一直都没有办法做到.
程式码(Code):(请善用置底文网页, 记得排版)
[Windows Code]
来源 http://ppt.cc/Gwcj
SOCKET RecvSocket;
unsigned short Port = 27015;
sockaddr_in RecvAddr;
RecvSocket = socket(AF_INET, SOCK_DGRAM, 0);
if (RecvSocket == INVALID_SOCKET) {
wprintf(L"socket error %d\n", WSAGetLastError());
return 1;
}
RecvAddr.sin_family = AF_INET;
RecvAddr.sin_port = htons(Port);
RecvAddr.sin_addr.s_addr = htonl(INADDR_ANY);
iResult = bind(RecvSocket, (SOCKADDR *) &RecvAddr,
sizeof (RecvAddr));
if (iResult != 0) {
wprintf(L"bind error %d\n", WSAGetLastError());
return 1;
}
...
若红色的地方换成下面
RecvAddr.sin_addr.s_addr = inet_addr("192.168.107.100");
则会印出黄色的部份
bind error 10049
问题1: 这边为什么会出现这种错误? 是不能bind这种ip吗?
[Linux Code]
struct sockaddr_in RecvAddr;
struct sockaddr_in CliAddr;
int lenCli = sizeof(CliAddr);
int len;
char buffer[4096];
int sock = socket(AF_INET, SOCK_DGRAM, 0);
RecvAddr.sin_family = AF_INET;
RecvAddr.sin_port = htons(Port);
RecvAddr.sin_addr.s_addr = inet_addr("192.168.107.100");
int rc = bind(sock, (struct sockaddr*)&RecvAddr, sizeof(RecvAddr));
if(rc < 0)
{
perror("bind error:");
return 0;
}
memset(&CliAddr, 0, sizeof(CliAddr));
len = recvfrom(sock, buffer, 4096, 0, (struct sockaddr*)&Cliaddr,
&lenCli);
if(len < 0)
{
perror("recvfrom error:");
return len;
}
....
问题2:
如果红色的部份是
RecvAddr.sin_addr.s_addr = htonl(INADDR_ANY);
可以收到封包, 但如果如红色那样子指定IP后,
就收不到封包了,
请教各位大大, 究竟要如何用才能让UDP接收指定IP的封包? 谢谢