- 论坛徽章:
- 0
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <strings.h>
#include <sys/socket.h>
#include <netinet/in.h>
void client()
{
sleep(3);
int childsock = socket(AF_INET,SOCK_STREAM,0);
if (childsock == -1)
{
perror("create socket in child");
exit(1);
}
struct sockaddr_in server;
bzero(&server,sizeof(server));
server.sin_family = AF_INET;
server.sin_port = htons(10000);
server.sin_addr.s_addr = inet_addr("127.0.0.1");
if (connect (childsock,(struct sockaddr*)&server,sizeof(struct sockaddr)) == -1)
{
perror("connect in child ");
exit(1);
}
close (childsock);
exit(0);
}
int main()
{
int i = 0;
for (; i < 10 ; i++)
{
pid_t child = fork ();
if (child == -1)
{
perror("fork");
exit(1);
}
else if (child == 0)
{
client();
}
}
int retcd;
int sock = socket(AF_INET,SOCK_STREAM,0);
if(sock == -1)
{
perror("socket");
exit(1);
}
int sopt = 1;
retcd = setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&sopt, sizeof(int));
if (retcd == -1)
{
perror("setsockopt");
}
struct sockaddr_in local;
bzero(&local,sizeof(local));
local.sin_family = AF_INET;
local.sin_port = htons(10000);
local.sin_addr.s_addr = INADDR_ANY;
if ( bind(sock,(struct sockaddr*)&local,sizeof(struct sockaddr)) == -1 )
{
perror("bind");
exit(1);
}
if ( listen(sock,10) == -1 )
{
perror("listen");
exit(1);
}
while (1)
{
struct sockaddr_in remote;
socklen_t len;
int newsock = accept(sock,&remote,&len);
printf("Request from %s\n",inet_ntoa(remote.sin_addr));
}
close(sock);
}
desktop:/data/learning/C/net # ./accept_sockaddr
Request from 0.0.0.0
Request from 127.0.0.1
Request from 127.0.0.1
Request from 127.0.0.1
Request from 127.0.0.1
Request from 127.0.0.1
Request from 127.0.0.1
Request from 127.0.0.1
Request from 127.0.0.1
每次运行结果的第一次IP 都不对 不知道为什么
请大家帮我分析分析
[ 本帖最后由 xiaozi16 于 2010-1-20 18:39 编辑 ] |
|