69,368
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/stat.h>
#define SERVPORT 110
#define MAX 4096
int main(int argc, char *argv[]) {
int sockfd, sendBytes, recvBytes;
char choice;
char buf[MAX];
struct hostent *host;
struct sockaddr_in servSockaddr;
if(argc != 2) {
fprintf(stderr,"usage:./client [hostname]\n");
//exit(1);
}
/*translate the address*/
if((host = gethostbyname(argv[1])) == NULL) {
perror("fail to get host by name\n");
exit(1);
}
/*establish a socket*/
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("fail to establish a socket\n");
exit(1);
}
/*init serverSockaddr*/
servSockaddr.sin_family = AF_INET;
servSockaddr.sin_port = htons(SERVPORT);
servSockaddr.sin_addr = *((struct in_addr *)host -> h_addr);
bzero(&(servSockaddr.sin_zero), 8);
/*connect the server*/
if(connect(sockfd, (struct sockaddr *)&servSockaddr, sizeof(struct sockaddr_in)) == -1) {
perror("fail to connect the socket\n");
exit(1);
}
printf("Success to connect the server!\n");
printf("Welcome to join %s!\n", inet_ntoa(servSockaddr.sin_addr));
}