代码:
服务端:
#include "/home/ubuntu/网络编程/myinc.h"
void* t1(void *arg)
{
sleep(2);
int acc_ret = *(int *)arg;
//接受通信
char *buf=malloc(100);
while(1)
{
memset(buf,0,100);
recv(acc_ret,buf,100,0);
printf("客户端:%s \n",buf);
}
free(buf);
close(acc_ret);
}
int main(int argc, const char *argv[])
{
//创建套接字
int sock_fd = socket(AF_INET,SOCK_STREAM,0);
//绑定服务器地址
struct sockaddr_in sock;
sock.sin_family = AF_INET;
sock.sin_port = htons(atoi(argv[2]));
sock.sin_addr.s_addr = inet_addr(argv[1]);
bind(sock_fd,(struct sockaddr *)&sock,sizeof(sock));
//监听
listen(sock_fd,4);
//定义一个线程号
pthread_t tid;
//创建线程
int acc_ret;
struct sockaddr_in client_addr;
while(1)
{
//等待连接
printf("等待连接\n");
acc_ret = accept(sock_fd,NULL,NULL);
printf("端口号%s连接成功\n",argv[2]);
char client_ip[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &(client_addr.sin_addr), client_ip, sizeof(client_ip));
printf("客户端IP地址: %s\n", client_ip);
printf("客户端端口号: %d\n", ntohs(client_addr.sin_port));
pthread_create(&tid,NULL,t1,&acc_ret);
}
return 0;
}
客户端:
#include "/home/ubuntu/IO/myinc.h"
int main(int argc, const char *argv[])
{
//1.创建套接字
int sock_fd = socket(AF_INET, SOCK_STREAM, 0);
//2.绑定服务器地址
/*特殊地址结构体 —— IPv4 地址结构体:
struct sockaddr_in
{
u_short sin_family; // 地址族
u_short sin_port; // 端口,0-----1023, 1024-----5000,5000------65535
struct in_addr sin_addr; // IPV4 地址
char sin_zero[8];
};
struct in_addr
{
in_addr_t s_addr; // 无符号 32 位网络地址sockaddr. sin_addr. s_addr = htons(192.168.124.195)
}; */
//定义结构体
struct sockaddr_in sock;
sock.sin_family = AF_INET;
sock.sin_port = htons(atoi(argv[2]));
sock.sin_addr.s_addr = inet_addr(argv[1]);
bind(sock_fd, (struct sockaddr *) &sock, sizeof(sock));
//3.发起连接
int con_ret = connect(sock_fd, (struct sockaddr *) &sock, sizeof(sock));
if( -1 == con_ret)
{
perror("connect failed");
return -1;
}
char *buf = malloc(100);
//4.发送数据
while(1)
{
memset(buf , 0 ,100);
fgets(buf,100,stdin);
send(sock_fd, (void *)buf, 100, 0);
}
}
头文件:
#ifndef __MYSTD__
#define __MYSTD__
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <semaphore.h>
#include <signal.h>
#include <pthread.h>
#include <dirent.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#endif