linux下c语言socket server_C/C++_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > C/C++ > linux下c语言socket server

linux下c语言socket server

 2010/12/8 10:17:00  cmzx3444  http://cmzx3444.javaeye.com  我要评论(0)
  • 摘要:/*============================================================================Name:socket.cAuthor:Version:Copyright:YourcopyrightnoticeDescription:HelloWorldinC,Ansi
  • 标签:Server Linux C语言 socket
/*
 ============================================================================
 Name        : socket.c
 Author      : 
 Version     :
 Copyright   : Your copyright notice
 Description : Hello World in C, Ansi-style
 ============================================================================
 */

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

const int MAXLINE = 1024;
int main(void) {

	int sockfd, clientfd;
	socklen_t cliaddr_len;
	struct sockaddr_in server_addr, client_addr;

	sockfd = socket(AF_INET, SOCK_STREAM, 0);

	if (sockfd == -1) {
		perror("出错了");
		exit(1);
	}

	bzero(&server_addr, sizeof(server_addr));

	server_addr.sin_family = AF_INET;
	server_addr.sin_port = htons(1024);
	server_addr.sin_addr.s_addr = htonl(INADDR_ANY);

	int br =
			bind(sockfd, (struct sockaddr *) &server_addr, sizeof(server_addr));
	if (br == -1) {
		perror("出错了");
		exit(1);
	}

	if ((listen(sockfd, 20)) == -1) {
		perror("出错了");
		exit(1);
	}

	char buf[MAXLINE];
	for (;;) {
		clientfd = accept(sockfd, (struct sockaddr *) &client_addr,
				&cliaddr_len);
		printf("server get connection from %s.\n", inet_ntoa(
				client_addr.sin_addr));
		int readize = 0;
		while ((readize = read(clientfd, buf, MAXLINE)) > 0) {
			printf("内容:%.*s", readize,buf);
			printf("长度:%d...\n", readize);
		}
		write(clientfd, buf, readize);
		close(clientfd);
	}
	return EXIT_SUCCESS;
}

发表评论
用户名: 匿名