87 lines
1.7 KiB
C
87 lines
1.7 KiB
C
|
#include <sys/stat.h>
|
|||
|
#include <fcntl.h>
|
|||
|
#include <errno.h>
|
|||
|
#include <netdb.h>
|
|||
|
#include <sys/types.h>
|
|||
|
#include <sys/socket.h>
|
|||
|
#include <netinet/in.h>
|
|||
|
#include <arpa/inet.h>
|
|||
|
#include <stdio.h>
|
|||
|
#include <string.h>
|
|||
|
#include <stdlib.h>
|
|||
|
#include <unistd.h>
|
|||
|
|
|||
|
|
|||
|
/*
|
|||
|
连接到服务器后,会不停循环,等待输入,
|
|||
|
输入quit后,断开与服务器的连接
|
|||
|
*/
|
|||
|
|
|||
|
int main()
|
|||
|
|
|||
|
{
|
|||
|
|
|||
|
int clientfd;
|
|||
|
struct sockaddr_in serverAddr;
|
|||
|
char sendbuf[200];
|
|||
|
char recvbuf[200];
|
|||
|
int iDataNum;
|
|||
|
char a[] = "192.168.209.193";
|
|||
|
char *str = a;
|
|||
|
int port = 61;
|
|||
|
|
|||
|
if((clientfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
|
|||
|
{
|
|||
|
printf("socket error");
|
|||
|
return -1;
|
|||
|
}
|
|||
|
|
|||
|
bzero(&serverAddr, sizeof(serverAddr));
|
|||
|
serverAddr.sin_family = AF_INET;
|
|||
|
serverAddr.sin_port = htons(port);
|
|||
|
printf("the value of str:%s\n", str);
|
|||
|
//将字符串的IP地址转化为网络字节序
|
|||
|
int ret = inet_pton(AF_INET, str, &serverAddr.sin_addr);
|
|||
|
printf("the value of ret is:%d\n",ret);
|
|||
|
printf("inet_pton:0x%x\n", serverAddr.sin_addr.s_addr);
|
|||
|
if(ret < 0)
|
|||
|
{
|
|||
|
printf("error");
|
|||
|
return -1;
|
|||
|
|
|||
|
}
|
|||
|
|
|||
|
int i = connect(clientfd, (struct sockaddr *)&serverAddr, sizeof(serverAddr));
|
|||
|
printf("the value of i is:%d\n", i);
|
|||
|
|
|||
|
if(i < 0)
|
|||
|
{
|
|||
|
fprintf(stderr, "socket connect error=%d(%s)\n", errno, strerror(errno));
|
|||
|
return -1;
|
|||
|
}
|
|||
|
|
|||
|
printf("连接到主机...\n");
|
|||
|
|
|||
|
while(1)
|
|||
|
{
|
|||
|
printf("发送消息:");
|
|||
|
scanf("%s", sendbuf);
|
|||
|
printf("\n");
|
|||
|
|
|||
|
send(clientfd, sendbuf, strlen(sendbuf), 0);
|
|||
|
if(strcmp(sendbuf, "quit") == 0)
|
|||
|
break;
|
|||
|
|
|||
|
printf("读取消息:");
|
|||
|
recvbuf[0] = '\0';
|
|||
|
iDataNum = recv(clientfd, recvbuf, 200, 0);
|
|||
|
recvbuf[iDataNum] = '\0';
|
|||
|
printf("%s\n", recvbuf);
|
|||
|
}
|
|||
|
|
|||
|
close(clientfd);
|
|||
|
return 0;
|
|||
|
|
|||
|
}
|
|||
|
|