BSD Sockets 使用的最廣泛的網絡程式程式設計方法,主要用于應用程式的編寫,用于網絡上主機與主機之間的互相通信.
UNIX,Linux,VxWorks均支援BSD Sockets,Windows的Winsock基本上是來自BSD Sockets
Socket分為Stream Sockets和Data Sockets.
Stream Sockets是可靠性的雙向資料傳輸用TCP,如HTTP,FTP等
Data Sockets是不可靠連接配接用UDP,如多點廣播,DHCP,SNMP,RIP等.
- TCP伺服器端和一個TCP用戶端通信的程式過程
伺服器 | 客戶機 |
| 兩個淺藍色的函數是兩個Sockets的握手函數,即在這裡建立連接配接 |
|
- UDP伺服器端和一個UDP用戶端通信的程式過程
伺服器 | 客戶機 |
|
這裡不建立連接配接,隻是資料收發 <----------
|
|
UDP廣播包程式示例
發送UDP廣播包,查找本地網絡中所有運作SNMP服務裝置的IP資訊。
winsock, win32控制台程式。
#define SNMP_PORT 161
void SearchIP_In_LAN()
{
WSADATA wsaData;
SOCKET sockListener;
SOCKADDR_IN saUdpCli,saUdpServ;
BOOL fBroadcast = TRUE;
char sendBuff[40]= //SNMP查詢包内容
{
'\x30','\x26','\x02','\x01','\x00',
'\x04','\x06','\x70','\x75','\x62',
'\x6c','\x69','\x63','\xa0','\x19',
'\x02','\x01','\x03','\x02','\x01',
'\x00','\x02','\x01','\x00','\x30',
'\x0e','\x30','\x0c','\x06','\x08',
'\x2b','\x06','\x01','\x02','\x01',
'\x01','\x01','\x00','\x05','\x00'
};
char recvBuff[600];
int nSize,err,timeoutnum = 1;;
ULONG HostIpAddr;
int rv;
int ncount=0;
if(WSAStartup(MAKEWORD( 2, 2),&wsaData)!=0)
{
printf("Winsocket start error!\n");
return;
}
sockListener=socket(AF_INET,SOCK_DGRAM,0);
err = setsockopt ( sockListener,
SOL_SOCKET,
SO_BROADCAST,
(CHAR *)&fBroadcast,
sizeof ( BOOL ));
if ( SOCKET_ERROR == err ) return ;
int TimeOut=10000;
err = setsockopt ( sockListener,
SOL_SOCKET,
SO_RCVTIMEO,
(CHAR *) &TimeOut,
sizeof (TimeOut)
);
if ( SOCKET_ERROR == err ) return ;
saUdpCli.sin_family = AF_INET;
saUdpCli.sin_port = htons(0);
saUdpCli.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind( sockListener, (SOCKADDR *)&saUdpCli, sizeof(SOCKADDR_IN))!=0)
{
printf("Can't bind socket to local port!Program stop.\n");
return;
}
err = gethostname(recvBuff,sizeof(recvBuff));
if ( SOCKET_ERROR == err )
return ;
struct hostent *hp = gethostbyname(recvBuff);
if (!hp) return ;
saUdpServ.sin_family = AF_INET;
memcpy(&(saUdpServ.sin_addr),hp->h_addr,hp->h_length);
HostIpAddr=ntohl(saUdpServ.sin_addr.s_addr);
saUdpServ.sin_addr.s_addr = htonl ( INADDR_BROADCAST );
saUdpServ.sin_port = htons (SNMP_PORT);
nSize = sizeof ( SOCKADDR_IN );
if((rv = sendto ( sockListener,
sendBuff,
sizeof(sendBuff),0,
(SOCKADDR *) &saUdpServ,
sizeof ( SOCKADDR_IN )))==SOCKET_ERROR)
{
printf("Send error!\n");
closesocket(*((SOCKET*)sockListener));
return;
}
printf("Send successful!\n");
do // waiting to receive
{
if((rv=recvfrom ( sockListener,
recvBuff,sizeof(recvBuff),0,
(SOCKADDR *) &saUdpCli,&nSize))==SOCKET_ERROR)
{
if(WSAGetLastError()==WSAETIMEDOUT)
{
if (timeoutnum > 6 ) //Wait for 1 minute.
break;
else
timeoutnum++;
}
}
else
{
CString Ip(inet_ntoa ( saUdpCli.sin_addr ));
printf("\t IP Adress-> %s ",Ip);
}
}while(TRUE);
closesocket(*((SOCKET*)sockListener));
return ;
}
網絡軟體設計框圖(個人了解,僅供參考)
- 裝置管理服務軟體架構
|
- 資訊家電(IA)的架構
|
- 無線移動通信的架構
|