tcp_client.c

来自「一个基于linux的TCP/IP协议栈的实现」· C语言 代码 · 共 67 行

C
67
字号
#include <stdio.h>#include <sys/types.h>#include <sys/socket.h>#include <string.h>#include "my_inet.h"#include <arpa/inet.h>int main(void){	int fd, n, r;	struct sockaddr_in srv, client;		srv.sin_family = MY_AF_INET;	srv.sin_port = htons(5002);	inet_aton("172.16.48.1", &srv.sin_addr);	client.sin_family = MY_AF_INET;	client.sin_port = htons(10000);	client.sin_addr.s_addr = inet_addr("172.16.48.13");	if( (fd = socket( MY_AF_INET, SOCK_STREAM, MY_IPPROTO_TCP) ) < 0 ){		perror("socket");		return -1;	}	if( bind(fd, (struct sockaddr *)&client, sizeof(client) ) < 0 ){		perror("bind: ");		return -1;	}	if( connect(fd, (struct sockaddr *)&srv, sizeof(srv)) < 0 ){		perror("connect: ");		return -1;	}	printf("send msg!\n");	char send_buf[4096];	strcpy( send_buf, "my first tcp packet!\n" );	memset(send_buf, 'a', 4095);	send_buf[4095] = '\0';	int len;	printf("start here!\n");	len = send(fd, send_buf, strlen(send_buf), 0 );	printf("after sned!\n");	printf("the len: %d\n", len );	if( len < 0 ){		printf("the return len: %d\n", len );		perror("send: ");		return -1;	}	if( recv( fd, send_buf, sizeof(send_buf), 0 ) < 0 ){		perror("recv: ");		return -1;	}	printf("recv from: %s\n", send_buf );	close(fd);/*		n = sizeof(cli);	while(1){		if( (r = recv(fd, buf, MAXBUF, 0)) < 0 ){			perror("recv:");		}else{			buf[r] = 0;			fprintf(stdout, "Mensaje desde: %s", buf);		}	}*/}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?