tcp客户端通信

网络编程

客户端通信

代码

/*************************************************************************************
 *
 *  file name:  1.c
 *  author   : 	lu.ciana.598393@gmail.com
 *  date     :  2024/06/05
 *  function : 	tcp客户端通信
 *  note	 :  none
 *  CopyRight (c)   2024    lu.ciana.598393@gmail.com   All Right Reserved
 *
 ************************************************************************************/

#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/udp.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/tcp.h>
#include <unistd.h>

int main(int argc,char *argv[])
{
    char buf[128];
    int tcp_socket = socket(AF_INET,SOCK_STREAM, 0);
    if (argc != 2)
	{
		printf("Invalid argc");
		exit(1);
	}
	if (tcp_socket == -1)
	{
		fprintf(stderr, "tcp socket error,errno:%d,%s\n",errno,strerror(errno));
		exit(1);
	}
	struct sockaddr_in  client_addr;

	client_addr.sin_family 		= AF_INET; 						//协议族,是固定的
	client_addr.sin_port   		= htons(atoi(argv[1]));			//目标端口,必须转换为网络字节序
	client_addr.sin_addr.s_addr   = inet_addr(argv[2]);		//目标地址 "192.168.64.xxx"  已经转换为网络字节序  INADDR_ANY

    // bind(tcp_socket,(struct sockaddr *)&host_addr, sizeof(host_addr));
    int i = connect(tcp_socket,(struct sockaddr *)&client_addr,sizeof(client_addr));
    if(i<0)
    {
        fprintf(stderr, "connect error,errno:%d,%s\n",errno,strerror(errno));
		exit(1);
    }
    while(1)
    {
        printf("请输入你需要发送的内容\n");
        scanf("%s",buf);
        write(tcp_socket,buf,sizeof(buf));
        bzero(buf,sizeof(buf));
    }

}

运行结果

image
image

posted @ 2024-06-05 21:19  luxiaolim  阅读(24)  评论(0)    收藏  举报