简单的TCP接受在转发到客户端的套接口

//功能:客服端发送tcp包,服务器接受到并打印出来,并将包转换为大写后到客户端
//2015.9.10成功

#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
int port = 8000;

int main()
{
struct sockaddr_in sin,cliaddr;
struct sockaddr_in pin;
int sock_descriptor;
int temp_sock_descriptor;
int address_size;
char buf[16384];
int i, len;

sock_descriptor = socket(AF_INET, SOCK_STREAM, 0);//TCP连接
if (sock_descriptor == -1) {
perror("call to socket");
exit(1);
}

bzero(&sin, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = INADDR_ANY;//自动填入本机IP地址
sin.sin_port = htons(port);
if (bind(sock_descriptor, (struct sockaddr *)&sin, sizeof(sin)) == -1) {
perror("call to bind");
exit(1);
}
if (listen(sock_descriptor, 20) == -1) {
perror("call to listen");
exit(1);
}

printf("Accepting connections ...\n");
int addr_len=sizeof(struct sockaddr_in);
while(1)
{

int temp_sock_descriptor = accept(sock_descriptor, (struct sockaddr *)&pin,&address_size);
if (temp_sock_descriptor == -1) {
perror("call to accept");
exit(1);
}
if (recv(temp_sock_descriptor, buf, 16384, 0) == -1) {
perror("call to recv");
exit(1);
}

// for this server example, we just convert the
// characters to upper case:
len = strlen(buf);
for (i=0; i<len; i++) buf[i] = toupper(buf[i]);
//toupper将字符c转换为大写英文字母
printf("sendbuff=%s\n",buf);


// 再次 发回到客户端
if (send(temp_sock_descriptor, buf, len, 0) == -1) {
perror("call to send");
exit(1);
}
close(temp_sock_descriptor);
}
}

你可能感兴趣的:(简单的TCP接受在转发到客户端的套接口)