我试图编写一段代码,允许我在DLL文件中建立TCP连接。这是我的情况:我有一个ruby应用程序需要能够通过套接字发送和接收数据,但由于它将运行的环境,我无法访问本机ruby套接字方法。然而,我可以访问DLL文件并运行其中的函数,所以我想我会为winsock创建一个包装器。不幸的是,尝试在正常的C ++应用程序中使用一段应该连接到TCP套接字的代码会引发一系列LNK2019错误,而这些错误在我的生活中无法解决。
这是我用来连接的方法:
//Socket variable
SOCKET s;
//Establishes a connection to the server
int server_connect(char* addr, int port)
{
//Start up Winsock
WSADATA wsadata;
int error = WSAStartup(0x0202, &wsadata);
//Check if something happened
if (error)
return -1;
//Verify Winock version
if (wsadata.wVersion != 0x0202)
{
//Clean up and close
WSACleanup();
return -2;
}
//Get the information needed to finalize a socket
SOCKADDR_IN target;
target.sin_family = AF_INET; //Address family internet
target.sin_port = _WINSOCKAPI_::htons(port); //Port #
target.sin_addr.s_addr = inet_addr(addr);
//Create the socket
s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (s == INVALID_SOCKET)
{
return -3;
}
//Try connecting
if (connect(s, (SOCKADDR *)&target, sizeof(target)) == SOCKET_ERROR)
{
//Failed to connect
return -4;
}
else
{
//Success
return 1;
}
}
我收到的确切错误是:
Error 1 error LNK2019: unresolved external symbol _closesocket@4 referenced in function _server_disconnect [Project Path]
Error 2 error LNK2019: unresolved external symbol _connect@12 referenced in function _server_connect [Project Path]
Error 3 error LNK2019: unresolved external symbol _htons@4 referenced in function _server_connect [Project Path]
Error 4 error LNK2019: unresolved external symbol _inet_addr@4 referenced in function _server_connect [Project Path]
Error 5 error LNK2019: unresolved external symbol _socket@12 referenced in function _server_connect [Project Path]
Error 6 error LNK2019: unresolved external symbol _WSAStartup@8 referenced in function _server_connect [Project Path]
Error 7 error LNK2019: unresolved external symbol _WSACleanup@0 referenced in function _server_connect [Project Path]
Error 8 error LNK1120: 7 unresolved externals [Project Path] 1 1
非常感谢!
答案 0 :(得分:1)
这是预期的。在现代Windows系统上将项目与Ws2_32.lib
链接。您的可执行文件将获取具有相同名称的DLL。