计划赶不上变化

导航

tcpip客户端

#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>
#include <stdlib.h>

#define SA struct sockaddr

int main(int argc, const char *argv[])
{

	if(argc!=3)
	{
		fprintf(stderr,"please input ip and port!\n");
		exit(1);
	}


	//socket
	int sockfd=socket(AF_INET,SOCK_STREAM,0);
	if(sockfd==-1)
	{
		perror("fail to socket");
		exit(1);
	
	}

	struct sockaddr_in peeraddr;

	peeraddr.sin_family=AF_INET;
	peeraddr.sin_port=htons(atoi(argv[2]));
	peeraddr.sin_addr.s_addr=inet_addr(argv[1]);
	
	socklen_t len=sizeof(peeraddr);

	char buf[128];

 
	int ret_con=connect(sockfd,(SA*)&peeraddr,len);
	if(ret_con<0)
	{
		perror("fail to connect!");
		exit(1);
	
	}
	// 瀹㈡埛绔彧鏈変竴涓猣d
	while(1)
	{
		bzero(buf,sizeof(buf));

		fgets(buf,sizeof(buf),stdin);浠庣粓绔帴鏀跺埌buf涓�
		if(buf[strlen(buf)-1]=='\n')
			buf[strlen(buf)-1]='\0';

 
		send(sockfd,buf,strlen(buf),0);

		bzero(buf,sizeof(buf));
	 
		recv(sockfd,buf,sizeof(buf),0);
		printf("%s\n",buf);
	}

	return 0;
}

posted on 2019-05-20 11:07  张培粉  阅读(124)  评论(0编辑  收藏  举报