Linux Socket 程式設計小例

2021-06-08 13:51:23 字數 2709 閱讀 2474

/**

* tcp server program, it is a ****** example only.

* when client connect to server, send a welcome message and timestamp in server.

*/#include #include #include #include #include #include #include #define server_port 20000 // define the defualt connect port id

#define length_of_listen_queue 10 // length of listen queue in server

#define buffer_size 255

#define welcome_message "welcome to connect the server. "

int main(int argc, char** argv)

bzero( & servaddr, sizeof (servaddr));

servaddr.sin_family = af_inet;

servaddr.sin_port = htons(server_port);

servaddr.sin_addr.s_addr = htons(inaddr_any);

if (bind(servfd,( struct sockaddr * ) & servaddr, sizeof (servaddr)) < 0 )

if (listen(servfd,length_of_listen_queue) < 0 )

while(1)

strcpy(buf,welcome_message);

// inet_ntop(inet_addrstrlen,cliaddr.sin_addr,buf,buffer_size);

printf( " from client,ip:%s,port:%d\n " ,

inet_ntoa(cliaddr.sin_addr),ntohs(cliaddr.sin_port));

timestamp = time(null);

strcat(buf, " timestamp in server: " );

strcat(buf,ctime( & timestamp));

send(clifd,buf,buffer_size, 0 );

close(clifd);

} close(servfd);

return 0;

}

/**

* tcp client program, it is a ****** example only.

* connect to server, and echo a message from server.

*/#include #include #include #include #include #include #define server_port 20000 // define the defualt connect port id

#define client_port ((20001+rand())%65536) // define the defualt client port as a random port

#define buffer_size 255

#define reuqest_message "welcome to connect the server.\n"

void usage(char* name)

int main(int argc, char** argv)

if ((clifd = socket(af_inet,sock_stream, 0 )) < 0)

srand(time(null)); // initialize random generator

bzero(&cliaddr, sizeof (cliaddr));

cliaddr.sin_family = af_inet;

cliaddr.sin_port = htons(client_port);

cliaddr.sin_addr.s_addr = htons(inaddr_any);

bzero(&servaddr, sizeof(servaddr));

servaddr.sin_family = af_inet;

inet_aton(argv[ 1 ], & servaddr.sin_addr);

servaddr.sin_port = htons(server_port);

// servaddr.sin_addr.s_addr = htons(inaddr_any);

if (bind(clifd, (struct sockaddr* ) &cliaddr, sizeof (cliaddr)) < 0)

if (connect(clifd,( struct sockaddr * ) & servaddr, socklen) < 0)

length = recv(clifd, buf, buffer_size, 0);

if (length < 0)

printf("from server %s :\n\t%s", argv[1], buf);

close(clifd);

return 0;

}

linux socket 程式設計

兩段程式 可用於開發板和主機之間的資料傳輸,很管用!file client.c檔案傳輸客戶端程式示例 本檔案是客戶機的 include for sockaddr in include for socket include for socket include for printf include f...

linux socket程式設計

雙休日無聊透頂,看了四五集 反恐24小時 實在不想看了,於是就想搞linux的socket programming來玩玩,前期資料都準備好 早就想寫個看看了。首先,寫個簡單的client端的程式 呵,其實是copy!server端用的是網上當的乙個除錯工具 一開始用的是以前用過的乙個多執行緒執行的介...

Linux Socket程式設計 執行緒

本章主要列舉伺服器程式的各種網路模型,示例程式以及效能對比後面再寫。一 分類依據。伺服器的網路模型分類主要依據以下幾點 1 是否阻塞方式處理請求,是否多路復用,使用哪種多路復用函式 2 是否多執行緒,多執行緒間如何組織 3 是否多程序,多程序的切入點一般都是accept函式前 二 分類。首先根據是否...