開發平台(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的封包? 謝謝