Hi all:
I wrote a simple program to open a socket to localhost port 8201.
Codes:
......
if (WSAStartup(VERSION, &wsadata) != NO_ERROR)
{
WSACleanup();
return EXIT_FAILURE;
}
open_socket(serverName, port);
SOCKET open_socket (const char *serverName, const int port)
{
struct hostent *server = NULL;
SOCKADDR_IN serverAddress;
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock!= INVALID_SOCKET)
{
server = gethostbyname(serverName);
if (server == NULL)
{
sock = INVALID_SOCKET;
}
else
{
char *ip = server->h_addr;
SOCKADDR_IN serverAddress =
{
AF_INET,
htons(port),
{ip[0], ip[1], ip[2], ip[3]}
};
}
if (connect(sock, (SOCKADDR*) &serverAddress, sizeof(serverAddress))<0)
{
sock = INVALID_SOCKET;
printf("Connection failed.");
}
printf("Connection successed.");
}
return sock;
}
It always results in "INVALID_SOCKET". I am very confused. The header file I used is #include <winsock.h>.
Thanks