1.server.c
服務(wù)器端的代碼
#include<stdio.h>
#include<ctype.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<unistd.h>
# define E_MSG(str, value) do{perror(str); return (value);} while(0);
int main(void){
char buff[128];
char IP[32];
struct sockaddr_in serv, clie;
socklen_t cli_len;
int s_fd = socket(AF_INET, SOCK_STREAM, 0);
if(s_fd == -1) E_MSG("socket", -1);
//對(duì)serv變量的成員進(jìn)行初始化
serv.sin_family = AF_INET;
serv.sin_port = htons(8001);
serv.sin_addr.s_addr = htonl(INADDR_ANY);
int bb = bind(s_fd, (struct sockaddr *) &serv, sizeof(serv));
if(bb == -1) E_MSG("bind", -1);
//將s_fd設(shè)置為被動(dòng)鏈接僧凤,監(jiān)聽客戶端連接
//將客戶端的連接放入到未決隊(duì)列中
//此前要定義未決隊(duì)列的長度
listen(s_fd, 5);
while(1){
cli_len = sizeof(clie);
//從未決隊(duì)列中取出一個(gè)連接處理
//返回這個(gè)連接的描述符瘪贱,使用該描述符和客戶端通信
int c_fd = accept(s_fd, (struct sockaddr *)&clie, &cli_len);
if(c_fd == -1) E_MSG("accept", -1);
//到此時(shí)涡扼,三次握手成功怯伊,可以傳輸數(shù)據(jù)
//從c_fd中讀取客戶端發(fā)來的數(shù)據(jù)
//二進(jìn)制轉(zhuǎn)換成字符
inet_ntop(AF_INET, &clie.sin_addr, IP, 32);
printf("Cleint ip: %s\n", IP);
int r = read(c_fd, buff, 128);
int i;
for(i = 0; i < r; i++){
buff[i] = toupper(buff[i]);
}
//將處理結(jié)果回送
write(c_fd, buff, r);
close(c_fd);
}
return 0;
}
2.client.c
#include<stdio.h>
#include<string.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>
int main(void){
char buff[128];
struct sockaddr_in serv;
char *msg = "hello sky walker...\n";
//create an socket connection, return file descriptor;
int fd = socket(AF_INET, SOCK_STREAM, 0);
if(fd == -1) return -1;
serv.sin_family = AF_INET;
serv.sin_port = htons(8001);
//二進(jìn)制轉(zhuǎn)換
inet_pton(AF_INET, "127.0.0.1", &serv.sin_addr);
//使用fd向服務(wù)器發(fā)起連接
int c = connect(fd, (struct sockaddr *)&serv, sizeof(serv));
if(c == -1) return -1;
//三次握手成功岸霹,向服務(wù)器發(fā)送數(shù)據(jù)
write(fd, msg, strlen(msg) + 1);
//等待服務(wù)器回應(yīng)
int r = read(fd, buff, 128);
write(1, buff, r);
close(fd);
return 0;
}