我有一个c#gui,当单击一个按钮时会调用引用的c ++ dll。在c ++ dll中,我有以下代码
SOCKADDR_IN server;
server.sin_port=htons (54321);
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
// Connect to server.
int iResult = connect(Socket, (SOCKADDR *) & server, sizeof (server));
if (iResult == SOCKET_ERROR) {
long iError = WSAGetLastError();
if (iError == WSAEWOULDBLOCK)
printf("recv failed with error: WSAEWOULDBLOCK\n");
else
printf("recv failed with error: %ld\n", iError);
wprintf(L"connect function failed with error: %ld\n", WSAGetLastError());
iResult = closesocket(Socket);
if (iResult == SOCKET_ERROR)
wprintf(L"closesocket function failed with error: %ld\n", WSAGetLastError());
WSACleanup();
return 1;
}
在调用dll之前的c#调用程序和winll2在dll中建立的连接中,我有
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
TcpListener serverSocket = new TcpListener(localAddr,54321);
int requestCount = 0;
TcpClient clientSocket = default(TcpClient);
serverSocket.Start();
然后在调用dll之后我做了
//调用dll来运行连接代码
clientSocket = serverSocket.AcceptTcpClient();//hangs up here because dll can't Connect.
在c ++ dll中,当我介入Connect时,我得到错误10049,这是 WSAEADDRNOTAVAIL。
我在Connect通话中做错了什么?我选择了54321作为msdn示例之后的端口。 谢谢!
答案 0 :(得分:2)
从我所看到的情况来看,除非您未在此处提供代码,否则您尚未正确设置sin_addr
结构的SOCKADDR_IN
字段。它期望以网络字节顺序的IP地址。
您需要执行以下操作:
inet_pton(AF_INET, "127.0.0.1", &server.sin_addr);
来源:
http://msdn.microsoft.com/en-us/library/windows/desktop/cc805844(v=vs.85).aspx