winsock.h是socket1.0 winsock2.h是socket2.0
socket本来就是在unix系统下为C语言开发的一种基于TCP的传输协议 winsock只不过是把它移到windows系统上来罢了 当然是兼容c的 你可以下载socket独立的库来使用C调用 也可以使用其它编译器提供的库来调用 就看兼容程度了
#include
#include
#pragma comment(lib, "ws2_32.lib")
int main(int argc, char* argv[])
{
HOSTENT *host_entry;
char host_name[256];
int n;
struct WSAData wsadata;
int sock;
struct sockaddr_in srvaddr;
struct hostent *hp;
char data[1024];
char c;
int i = 0;
if(argc<3)
{
printf("Usage: %s ip port\n",argv[0]);
exit(1);
}
if(WSAStartup(0x0101,&wsadata)==0)
{
n = gethostname(host_name, 256);
host_entry=gethostbyname(host_name);
if(host_entry != NULL)
{
printf("%d.%d.%d.%d\n",
host_entry->h_addr_list[0][0]&0x00ff,
host_entry->h_addr_list[0][1]&0x00ff,
host_entry->h_addr_list[0][2]&0x00ff,
host_entry->h_addr_list[0][3]&0x00ff);
}
sock=socket(AF_INET,SOCK_STREAM,0);
if ( sock < 0 )
{
printf("socket create error.\n");
exit(1);
}
srvaddr.sin_family=AF_INET;
hp=gethostbyname(argv[1]);
if(hp==0)
{
printf("unknow host: %s\n",argv[1]);
exit(1);
}
memcpy((char*)&srvaddr.sin_addr,(char*)hp->h_addr,hp->h_length);
srvaddr.sin_port=htons((unsigned short)atoi(argv[2]));
if(connect(sock,(struct sockaddr*)&srvaddr,sizeof(srvaddr))<0)
{
printf("connect server error.\n");
exit(1);
}
while(1)
{
memset(data, 0, 1024);
i = 0;
c = getchar();
while ( c != 10 )
{
data[i++] = c;
c = getchar();
}
data[i] = '\0';
if ( send(sock, data, sizeof(data), 0) < 0 )
{
printf("send data error.\n");
exit(1);
}
if (recv(sock,data,1024,0) )
{
printf("----->%s\n",data);
}
if(strcmp(data, "bye")==0)
{
closesocket(sock);
printf("connecting close.\n");
WSACleanup();
exit(0);
}
}
}
WSACleanup();
return 0;
}
是封装好的API,也就是只有函数的部首,实现方法应该是C和一些汇编的混合。另外可以使用#include
winsock.h是windows C++ sdk的网络库的头文件
windows的C程序可以使用