当前位置: 技术问答>linux和unix
简单的socket出错!!!
来源: 互联网 发布时间:2017-05-28
本文导语: 服务器程序: #include #include #include #include #include #include #define SA struct sockaddr #define MAXLINE 1024 int main( void ) { int listenfd, connfd; struct sockaddr_in servaddr; char buff[ MAXLINE ]; time_t ticks; pid_t pid; listenfd =...
服务器程序:
客户端:
#include
#include
#include
#include
#include
#include
#define SA struct sockaddr
#define MAXLINE 1024
int main( void )
{
int listenfd, connfd;
struct sockaddr_in servaddr;
char buff[ MAXLINE ];
time_t ticks;
pid_t pid;
listenfd = socket( AF_INET, SOCK_STREAM, 0 );
bzero( &servaddr, sizeof( servaddr ) );
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htonl(13);
bind(listenfd, ( SA * )&servaddr, sizeof(servaddr));
listen( listenfd, 5 );
for( ; ; ){
connfd = accept( listenfd, ( SA * )NULL, NULL);
pid = fork();
if ( 0 == pid ){
ticks = time( NULL );
snprintf(buff, sizeof(buff), "%.24srn", ctime(&ticks));
write( connfd, buff, strlen(buff));
}
if ( waitpid(pid, NULL,0 ) != pid ){
printf("waitpid error");
exit(1);
}
close( connfd );
}
return 0;
}
客户端:
#include
#include
#include
#include
#include
#define SA struct sockaddr
#define MAXLINE 1024
int main( int argc, char **argv )
{
int sockfd, n;
char recvline[ MAXLINE + 1 ];
struct sockaddr_in servaddr;
if ( argc != 2 ){
printf("usage:a.out ");
exit(1);
}
if ( ( sockfd = socket( AF_INET, SOCK_STREAM, 0 ) )