超简洁的基础双向通信,使用sendto和recvforn函数,适合初学者。先启动server端,由cilent端发送字符串消息,然后再由server端发送消息。
增加了自动获取本机ip功能,
htons(SERVER_PORT); //注意网络序转换 ,也就是将主机字节顺序转换为网络字节顺序 。
server.cpp 服务端
#include <iostream>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <netdb.h>
using namespace std;
#define SERVER_PORT 1999
int main()
{
int sfd;
int ret;
struct sockaddr_in ser_addr;//服务器端的结构体
sfd= socket(AF_INET, SOCK_DGRAM, 0);
if (sfd < 0)
{
cout << "socket created fail" << endl;
return -1;
}
cout << "socket created successfully!" << endl;
char* ip;
int i;
char hname[128];
struct hostent* hent;
gethostname(hname, sizeof(hname));
hent = gethostbyname(hname);
for (i = 0; hent->h_addr_list[i]; i++)
{
ip = inet_ntoa(*(struct in_addr*)(hent->h_