//转自:《window网络编程》,其中部分代码已经过完善
//此程序包含一个文件:tcpclient.c
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
int main(int argc, char **argv)
{
WSADATA wsaData;
SOCKET s;
SOCKADDR_IN ServerAddr;
int Port = 5150;
int Ret;
if(argc <= 1)
{
printf("USAGE: <tcpclient<ServerIP>> \n");
return -1;
}
if((Ret = WSAStartup(MAKEWORD(2, 2), &wsaData)) != 0)
{
printf("WSAStartup failed with error %d \n", Ret);
return -1;
}
if((s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET)
{
printf("socket failed with error %d \n", WSAGetLastError());
WSACleanup();
return -1;
}
ServerAddr.sin_family = AF_INET;
ServerAddr.sin_addr.s_addr = inet_addr(argv[1]);
ServerAddr.sin_port = htons(Port);
printf("We are trying to connect %s : %d ...\n", inet_ntoa(ServerAddr.sin_addr), ntohs(ServerAddr.sin_port));
if((connect(s, (SOCKADDR*)&ServerAddr, sizeof(ServerAddr))) == SOCKET_ERROR)
{
printf("connect failed with error %d \n", WSAGetLastError());
closesocket(s);
WSACleanup();
return -1;
}
printf("our connection succeed! \n");
printf("We will now try to send a hello message! \n");
if((Ret = send(s, "hello", 5, 0)) == SOCKET_ERROR)
{
printf("send failed with error %d \n", WSAGetLastError());
closesocket(s);
WSACleanup();
return -1;
}
printf("We have sent %d type(s). \n", Ret);
printf("We are trying to close the connection. \n");
closesocket(s);
WSACleanup();
return 0;
}