#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <string.h>
#include <arpa/inet.h> //定义sockaddr_in
#include <unistd.h>
#include <signal.h>
#define PORT 3333
#define MAX_SIZE 1024
int main(int argc,char ** argv){
if(argc != 2){
printf("please input server ip\n");
exit(1);
}
int sockfd; //创建通信节点的:文件描述符
struct sockaddr_in server_addr;
char buffer[MAX_SIZE];
int n_write;
if((sockfd = socket(AF_INET,SOCK_STREAM,0)) < 0){
perror("socket success!\n");
exit(1);
}
printf("socket success!\n");
bzero(&server_addr,0);
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(PORT);
server_addr.sin_addr.s_addr = inet_addr(argv[1]);
//在套接字上启动连接
//int connect(int sockfd, const struct sockaddr *addr,socklen_t addrlen);
//成功返回0,失败返回-1
//包含第一,三次握手
if(connect(sockfd,(struct sockaddr *)&server_addr,(socklen_t)sizeof(server_addr)) < 0){
perror("connect server error!\n");
exit(1);
}
printf("connect success!\n");
while(1){
memset(buffer,0,sizeof(buffer));
printf("please input send msg:\n");
scanf("%s",buffer);
n_write = write(sockfd,buffer,(size_t)sizeof(buffer));
if(n_write < 0){
perror("send to server msg error!\n");
exit(1);
}
}
return 0;
}
linux下网络通信客户端(普通)
最新推荐文章于 2023-01-26 10:00:00 发布