日期:2014-05-16 浏览次数:20775 次
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int create_TCPClient(const char *serverIP,unsigned short port)
{
int sockfd;
int ret;
struct sockaddr_in client_sock;
sockfd=socket(AF_INET,SOCK_STREAM,0);
if(sockfd==-1)
{
perror("socket:");
return -1;
}
//自己IP和自己的port内核自动设置
memset(&client_sock,0,sizeof(client_sock));
client_sock.sin_family = AF_INET;
client_sock.sin_port = htons(port);
client_sock.sin_addr.s_addr = inet_addr(serverIP);
ret = connect(sockfd,(struct sockaddr *)&client_sock,sizeof(client_sock));
if(ret == -1){
perror("connect");
return -1;
}
return sockfd;
}
int main(int argc,char *argv[])
{
int sockfd,n;
unsigned short port;
char buf1[20]="GET / HTTP/1.0";
char buf2[100];
if(argc!=3)
{
printf("usage:client <serverIP> <port>\n");
exit(1);
}
port=(unsigned int )atoi(argv[2]);
sockfd=create_TCPClient(argv[1],port);
if(sockfd!=-1) printf("connect success!\n");
else
{
perror("connect:");
exit(1);
}
n=write(sockfd,buf1,20);
if(n==0) {perror("write:");exit(1);}
while(read(sockfd,buf2,100)>0)
{
printf("%s\n",buf2);
}
exit(0);
}