📄 client.c
字号:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <netinet/in.h>
#include <sys/socket.h>
#define SERVERPORT 3333
#define MAXSIZE 8192
int main(int argc,char *argv[])
{
int fd, readsize;
int sockfd, connectfd, sendbytes;
char buf[MAXSIZE] = "hello";
struct hostent *host;
struct sockaddr_in server_addr;
if(argc < 2) {
printf("Please enter the server's hostname!\n");
exit(1);
}
host = gethostbyname(argv[1]);
if(host == NULL) {
printf("gethostbyname error!!!\n");
exit(1);
}
else
printf("gethostbyname success!!!\n");
sockfd = socket(AF_INET,SOCK_STREAM,0);
if(sockfd == -1) {
printf("Create a socket error!!!\n");
exit(1);
}
else
printf("sockfd success!!! sockfd = %d\n",sockfd);
server_addr.sin_family=AF_INET;
server_addr.sin_port=htons(SERVERPORT);
server_addr.sin_addr=*((struct in_addr *)host->h_addr);
memset(server_addr.sin_zero, 0, sizeof(server_addr.sin_zero));
connectfd = connect(sockfd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr));
if(connectfd == -1) {
printf("connect error!!!\n");
exit(1);
}
else
printf("connect success!!!\n");
fd = open("/home/hongzhi/UNIX/linux_code/10/client.c", O_RDONLY);
do {
readsize = read(fd, buf, sizeof(buf));
sendbytes = send(sockfd,buf,readsize,0);
if(sendbytes == -1) {
printf("send error!!!\n");
exit(1);
}
else
if(sendbytes > 0)
printf("send success!!! sendbytes = %d\n",sendbytes);
else
printf("send end!!!\n");
memset(buf, 0, sizeof(buf));
} while(readsize > 0);
close(sockfd);
close(fd);
return 0;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -