今天第一次接触winsock网络编程,看的资料是Windows网络编程第二版。通过博客记住自己的看书笔记。。
在这里贴出第一个程序,虽然程序什么都没做,但以此作为入门,熟悉其网络编程风格。。
1 #include"winsock2.h" 2 #include<iostream> 3 using namespace std; 4 //This line is very important 5 6 #pragma comment(lib,"ws2_32.lib") 7 int main() 8 { 9 WSADATA wsaData; 10 int Ret; 11 //WSAStartup to initialize the Winsock version 12 Ret = WSAStartup(MAKEWORD(2,2),&wsaData); 13 if(Ret != 0) 14 { 15 cout<<"WSAStartup failed with error "<<Ret<<endl; 16 return -1; 17 } 18 if (WSACleanup() == SOCKET_ERROR) 19 { 20 cout<<"WSACleanup failed with error "<<WSAGetLastError()<<endl; 21 return -1; 22 } 23 24 return 0; 25 }
入门当然少不了的是概念。。所以在此也列举出今天看书遇到的几个陌生概念。。
例:如果我们将0x1234abcd写入到以0x0000开始的内存中,则结果为:
big-endian little-endian
0x0000 0x12 0xcd
0x0001 0x23 0xab
0x0002 0xab 0x34
0x0003 0xcd 0x12
有关主机字节和网络字节之间的相互转换如下:
主机字节转换为网络字节:
u_long htonl(u_long hostlong);
int WSAHtonl(SOCKET s,u_long hostlong,u_long FAR* lpnetlong);
u_short htonl(u_short hostshort);
int WSAHtonl(SOCKET s,u_short hostshort,u_short FAR* lpnetshort);
逆转换,网络字节转换为主机字节:
u_long ntohl(u_long netlong);
int WSANtohl(SOCKET s,u_long netlong,u_long FAR* lphostlong);
u_short ntonl(u_short netshort);
int WSANtonl(SOCKET s,u_short netshort,u_short FAR* lphostshort);
下面的代码是演示有关网络中ip和port的初始化。。
1 #include"winsock2.h" 2 #include<iostream> 3 using namespace std; 4 //This line is very important 5 6 #pragma comment(lib,"ws2_32.lib") 7 int main() 8 { 9 WSADATA wsaData; 10 int Ret; 11 //WSAStartup to initialize the Winsock version 12 Ret = WSAStartup(MAKEWORD(2,2),&wsaData); 13 if(Ret != 0) 14 { 15 cout<<"WSAStartup failed with error "<<Ret<<endl; 16 return -1; 17 } 18 19 //note the definition of SOCKADDR_IN 20 SOCKADDR_IN InternetAdd; 21 INT portID = 5016;//here we assume that the ip is 136.149.3.29,port is 5016 22 23 InternetAdd.sin_family = AF_INET;//address family 24 InternetAdd.sin_addr.s_addr = inet_addr("136.149.3.29"); 25 InternetAdd.sin_port = htons(portID); 26 27 if (WSACleanup() == SOCKET_ERROR) 28 { 29 cout<<"WSACleanup failed with error "<<WSAGetLastError()<<endl; 30 return -1; 31 } 32 33 return 0; 34 }
Winsock 网络编程笔记(1)----入门,布布扣,bubuko.com
原文地址:http://www.cnblogs.com/LCCRNblog/p/3836423.html