Linux高级网络编程网络通信客户端代码

来源:互联网 发布:php取数组最大值 编辑:程序博客网 时间:2024/06/07 14:32
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>


int create_tcp_client(const char *ip,unsigned short port)
{


int sk;
int ret;
struct sockaddr_in dest;
pid_t pid;

/* 先选择socket的功能 */
sk = socket(AF_INET, SOCK_STREAM, 0);
if(sk < 0){
perror("socket");
return -1;
}

memset(&dest,0,sizeof(dest));
dest.sin_family = AF_INET;
dest.sin_port = htons(port);
inet_aton(ip,&dest.sin_addr);


ret = connect(sk,(const struct sockaddr *)&dest,sizeof(dest));
if(ret == -1){
perror("connect");
return -1;
}
printf("connect success!\n");
return sk;
}


int main(int argc,char *argv[])
{
int sockfd;
char buf1[100];
char buf2[100];
int ret;
int len;
pid_t pid;
if(argc != 3){
printf("usage ./build ip port\n");
exit(1);
}

sockfd = create_tcp_client(argv[1],atoi(argv[2]));
if(sockfd < 0 ){
printf("create tcp client failed!\n");
exit(1);
}
pid = fork();
if(pid == -1)
{
printf("fork error!!!\n");
exit(1);
}

if(pid ==0)
{
while(1)
{
len = read(sockfd,buf2,100);
if(len > 0)
{
buf2[len] = '\0';
printf("Recoved:%s\n",buf2);
}
if(len ==  0)
{
close(sockfd);
exit(0);
}

}
}
else
{
while(1)
{
fgets(buf1, 100, stdin); 
if(strncmp(buf1,"quit", 4) == 0) 
{
kill(pid,5);
wait(NULL);
printf("close the program!!\n");
close(sockfd);
exit(0);
}
write(sockfd, buf1, strlen(buf1));
}

}
close(sockfd);
}





















0 0
原创粉丝点击