Here my socket.c as server simply listen on a port: the succinct code like below, I just want the code listening but not exit the process.
#include <stdio.h>
#include <stdlib.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#define DEFAULT_PORT 27015
int main(int argc, char *argv[]) {
int so = socket(0,1,0);
struct sockaddr_in serv_addr, cli_addr;
bzero(&serv_addr,sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(DEFAULT_PORT);
listen(so,5);
accept(so,NULL,NULL);
return 0;
}
absolutely some hard code in here. but when I gcc a.c compile it and run it. it will exit rather than listening.
So what's wrong with my code ????????????
答案 0 :(得分:2)
You're not creating a stream socket over AF_INET
that's why its not listening to the socket.
The code for AF_INET
is 2
and not 0
.
change the code as
int so = socket(AF_INET, SOCK_STREAM, 0);
or
int so = socket(2, 1, 0);
it will work
You also need to bind the port number on which the server will listen. Binding is not must for client
port but is a must for Server
port number
bind(so, (struct sockaddr *)&serv_addr, sizeof(serv_addr));