Unix网络编程之socket编程(一)--socket入门简单程序

本程序实现客户端向服务器发送一个字符串,服务器将接收到的字符串回送给客户端。

// unp.h
#ifndef _UNP_H
#define _UNP_H

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

#define MAXLINE 4096
#define ERR_EXIT(m) \
		do{ \
			perror(m); \
			exit(EXIT_FAILURE); \
		  }while(0)

#endif
下面是客户端代码:

#include "unp.h"

int main()
{
	int sockfd;
	char sendbuff[MAXLINE];
	struct sockaddr_in servaddr;
	ssize_t n;
	
	if( (sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
		ERR_EXIT("socket err");
	
	memset(&servaddr, 0, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_port = htons(6666);
	servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");

	if(connect(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) < 0)
		ERR_EXIT("connect err");
	
	for(; ;){
		fgets(sendbuff, MAXLINE, stdin);
		if( (n = write(sockfd, sendbuff, strlen(sendbuff))) < 0)
			ERR_EXIT("write err");
		memset(sendbuff, 0 ,sizeof(sendbuff));
		
		if( (n = read(sockfd, sendbuff, sizeof(sendbuff))) < 0)
			ERR_EXIT("read err");
		fputs(sendbuff, stdout);
		memset(sendbuff, 0, sizeof(sendbuff));
	}

	close(sockfd);
}
下面是服务端代码:

#include "unp.h"

int main()
{
	int listenfd, connfd;
	struct sockaddr_in servaddr;
	char recvbuff[MAXLINE];
	ssize_t n;

	if( (listenfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
		ERR_EXIT("socket err");

	memset(&servaddr, 0, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_port = htons(6666);
	servaddr.sin_addr.s_addr = INADDR_ANY;
	
	if(bind(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) < 0)
		ERR_EXIT("bind err");

	if(listen(listenfd, SOMAXCONN) < 0)
		ERR_EXIT("listen err");

	if( (connfd = accept(listenfd, (struct sockaddr*)NULL, NULL)) < 0)
		ERR_EXIT("accept err");
	
	for(; ;){
		if( (n = read(connfd, recvbuff, sizeof(recvbuff))) < 0)
			ERR_EXIT("read err");
		recvbuff[n] = '\0';
		fputs(recvbuff, stdout);
		
		if( (n = write(connfd, recvbuff, strlen(recvbuff))) < 0)
			ERR_EXIT("write err");
		memset(recvbuff, 0, sizeof(recvbuff));
	}

	close(connfd);
	close(listenfd);

	return 0;
}



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值