23,121
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main()
{
int n;
int sockfd,newsockfd;
struct sockaddr_in sockadd,newsockadd;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
bzero(&sockadd,sizeof(struct sockaddr_in));
sockadd.sin_family = AF_INET;
sockadd.sin_port = htons(3633);
bind(sockfd, &sockadd, sizeof(struct sockaddr));
listen(sockfd, 2);
for(;;)
{
newsockfd = accept(sockfd, &newsockadd, sizeof(struct sockaddr));
printf("somebody has connected!!\n");
if(!fork())
{
while(1)
{
char buffer[101];
bzero(buffer,101);
int len = recv(newsockfd, buffer, 100,0);
if(len > 0)
{
printf("success\n");
printf("%d %s\n",len,buffer);
}else
{
//printf("%d\n",len);
}
}
}
}
close(sockfd);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
int main()
{
int sockfd;
struct sockaddr_in sockadd;
struct hostent *he;
he = gethostbyname("localhost");
bzero(&sockadd, sizeof(struct sockaddr));
sockadd.sin_family = AF_INET;
sockadd.sin_addr = *((struct in_addr *)he->h_addr);
sockadd.sin_port = htons(3633);
sockfd = socket(AF_INET,SOCK_STREAM, 0);
connect(sockfd, &sockadd, sizeof(struct sockaddr));
char buffer[101];
char revbuf[101];
int lenght;
while(1)
{
bzero(buffer,101);
scanf("%s",buffer);
lenght = send(sockfd, buffer, sizeof(buffer), 0);
if(lenght > 0)
printf("send %d %s success\n",lenght,buffer);
}
//close(sockfd);
return 0;
}