1服务器开发代码
#include<sys/socket.h>
#include<sys/types.h>
#include<string.h>
#include<errno.h>
#include<stdio.h>
#include<stdlib.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>
/* socket->bind->listen->accept->send/recv->close*/
int main()
{
int socket_fd;
int ret;
char buff[1024];
int lens;
socket_fd = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in server_addr;
struct sockaddr_in client_addr;
if (-1 == socket_fd)
{
fprintf(stderr, "socket error %s\n", strerror(errno)); // rerror
exit(0);
}
int issockeopet = 1;
//设置ip地址重复使用
setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, (const char*)&issockeopet, sizeof(int));
memset(&server_addr, 0, sizeof(struct sockaddr_in));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(8888);
server_addr.sin_addr.s_addr = INADDR_ANY;//自动接受任意IP地址
ret = bind(socket_fd, (const struct sockaddr*)(&server_addr), sizeof(struct sockaddr));
if (ret == -1)
{
fprintf(stderr, "bind error:%s\n", strerror(errno));
exit(0);
}
if (listen(socket_fd, 10) == -1)
{
fprintf(stderr, "listen error:%s\n", strerror(errno));
exit(0);
}
socklen_t len = sizeof(struct sockaddr_in);
bzero(&client_addr, sizeof(struct sockaddr_in));
int newfd = accept(socket_fd, (struct sockaddr*)&client_addr, &len);
if (newfd == -1)
{
fprintf(stderr, "accept error:%s\n", strerror(errno));
exit(0);
}
fprintf(stderr, "server connet form %s success\n", inet_ntoa(client_addr.sin_addr));
while (true)
{
lens = read(newfd, buff, strlen(buff) + 1);
if (lens == -1)
{
fprintf(stderr, "read error:%s\n", strerror(errno));
exit(0);
}
printf("rev %s \n", buff);
}
close(newfd);
close(socket_fd);
return 0;
}
2.客户端开发代码
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <string.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
//服务器的
int main(int argc, char* argv[])
{
int sock_fd;
int ret = 0;
char buff[1024] = {0};
struct sockaddr_in server_addr;
if (argc != 2)
{
fprintf(stderr,"user:./ip:%s\n",argv[0]);
}
sock_fd = socket(AF_INET, SOCK_STREAM, 0);
if (-1 == sock_fd)
{
fprintf(stderr, "socket error:%s\n\a", strerror(errno));
exit(1);
}
memset(&server_addr, 0, sizeof(struct sockaddr_in));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(8888);
ret =inet_aton(argv[1], &server_addr.sin_addr);
if (0==ret)
{
fprintf(stderr, "server_ip set error:\n");
close(sock_fd);
exit(1);
}
//server_addr.sin_addr=
ret=connect(sock_fd, (const struct sockaddr*)&server_addr, sizeof(struct sockaddr_in));
if (-1==ret)
{
fprintf(stderr, "connect set error:%s\n", strerror(errno));
close(sock_fd);
exit(0);
}
//发数据
while (1)
{
if (fgets(buff, 1024, stdin))
{
int lens=write(sock_fd, buff, strlen(buff)+1);
if (lens <= 0)
{
fprintf(stderr, "write set error:%s\n", strerror(errno));
close(sock_fd);
exit(1);
}
}
}
close(sock_fd);
return 0;
}