下面你可以看到我的代碼在C++中用Winsock實現了一個非常基本的UDP發送器。問題是無論我運行多少次代碼,套接字(listenSocket)都被綁定到不同的UDP端口。這有什麼特別的原因嗎?我在我的代碼中犯了一些錯誤嗎?winsock - 發件人UDP套接字沒有綁定到所需的端口
感謝
#include <cstdlib>
#include <iostream>
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
using namespace std;
int main(int argc, char *argv[])
{
WSADATA wsaData;
SOCKADDR_IN myAddress;
SOCKADDR_IN targetAddress;
int myPort = 60888;
const char *myIP = "192.168.0.1";
int remotePort = 2048;
const char *remoteIP = "192.168.0.2";
SOCKET ListenSocket = INVALID_SOCKET;
SOCKET SendSocket = INVALID_SOCKET;
SOCKET acceptSocket;
char cBuffer[1024] = "Test Buffer";
int nBytesSent = 0;
int nBufSize = strlen(cBuffer);
int iResult;
// Initialize Winsock
if(WSAStartup(MAKEWORD(2, 2), &wsaData) != NO_ERROR)
{
cerr<<"Socket Initialization: Error with WSAStartup\n";
system("pause");
WSACleanup();
exit(10);
}
ListenSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
SendSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (ListenSocket == INVALID_SOCKET or SendSocket == INVALID_SOCKET)
{
cerr<<"Socket Initialization: Error creating socket"<<endl;
system("pause");
WSACleanup();
exit(11);
}
//bind
myAddress.sin_family = AF_INET;
myAddress.sin_addr.s_addr = inet_addr(myIP);
myAddress.sin_port = htons(myPort);
targetAddress.sin_family = AF_INET;
targetAddress.sin_addr.s_addr = inet_addr(remoteIP);
targetAddress.sin_port = htons(remotePort);
if(bind(ListenSocket, (SOCKADDR*) &myAddress, sizeof(myAddress)) == SOCKET_ERROR)
{
cerr<<"ServerSocket: Failed to connect\n";
system("pause");
WSACleanup();
exit(14);
}
else
printf("Server: bind() is OK.\n");
nBytesSent = sendto(SendSocket, cBuffer, nBufSize, 0,
(SOCKADDR *) &targetAddress,
sizeof(SOCKADDR_IN));
printf("Everything is ok\n");
system("PAUSE");
closesocket(ListenSocket);
closesocket(SendSocket);
return EXIT_SUCCESS;
}
編輯:也許我不是那麼清晰。我用這個代碼做什麼是發送一些數據到遠程PC。但是需要的是,UDP段看起來應該來自特定的端口。如何才能做到這一點?我在這裏做什麼錯了?現在我正在考慮這個問題,我猜這確實是錯誤的。 SendSocket和ListenSocket沒有任何連接,對嗎?那麼,我怎樣才能使UDP段看起來來自特定的UDP端口呢?謝謝!
謝謝你的澄清,我真的很困惑(雖然它很簡單)。無論我們是收聽傳入的數據還是從此套接字發送,我都沒有意識到套接字可以綁定到本地ip /端口。 – nickagian