linux socket常规操作

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

#define PORT 3333
#define BACKLOG 10
#define DATASIZE 10

int main(int argc, char **argv) {
	int sockfd, client_fd;
	struct sockaddr_in serv_addr;
	struct sockaddr_in remote_addr;
	char buf[DATASIZE];
	int recv_len;

	if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
		perror("socket error");
		exit(1);
	}

	bzero(&(serv_addr), sizeof(serv_addr));
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_port = htons(PORT);
	serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);

	int opt = 1;
	if(setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (void*)&opt, sizeof(int)) == -1) {
		perror("setsocket error");
		exit(1);
	}

	if(bind(sockfd, (struct sockaddr*)&serv_addr, sizeof(struct sockaddr)) == -1) {
		perror("bind error");
		exit(1);
	}

	if(listen(sockfd, BACKLOG) == -1) {
		perror("listen error");
		exit(1);
	}

	size_t sin_size = sizeof(struct sockaddr_in);
	if((client_fd = accept(sockfd, (struct sockaddr*)&remote_addr, &sin_size)) == -1) {
		perror("accept error");
		exit(1);
	}
	printf("receive a connection from %s\n", inet_ntoa(remote_addr.sin_addr));

	while(1) {
		bzero(buf, sizeof(buf));
		recv_len = recv(client_fd, buf, DATASIZE, 0);
		//buf[DATASIZE] = '\n';
		fprintf(stdout, "%s", buf);
	}
	close(sockfd);
}
telnet localhost 3333
/*client*/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>

#define PORT 3333
#define MAXDATASIZE 100

int main(int argc, char **argv) {
	int sockfd, recvbytes;
	char buf[MAXDATASIZE];
	struct sockaddr_in serv_addr;
	struct hostent *host;

	if(argc < 2) {
		fprintf(stderr, "Please enter the server's hostname\n");
		exit(1);
	}

	if((host = gethostbyname(argv[1])) == NULL) {
		perror("gethostbyname error");
		exit(1);
	}

	printf("host name: %s\n", host->h_name);
	printf("host address: %s\n", inet_ntoa(*((struct in_addr*)host->h_addr)));

	if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
		perror("socket error");
		exit(1);
	}

	bzero(&serv_addr, sizeof(struct sockaddr_in));
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_port = htons(PORT);
	serv_addr.sin_addr = *((struct in_addr*)host->h_addr);

	if(connect(sockfd, (struct sockaddr*)&serv_addr, sizeof(struct sockaddr)) == -1) {
		perror("bind error");
		exit(1);
	}

	if((recvbytes = recv(sockfd, buf, MAXDATASIZE, 0)) == -1) {
		perror("recv error");
		exit(1);
	}

	buf[recvbytes] = '\0';
	printf("Recvived: %s", buf);

	close(sockfd);
}