I am learning socket program in ubuntu for which I wrote the following program for server client communication. The program is not opening the ports. I also have some other questions regarding server client communications:
- When the server accepts the client request, does server starts reading from client the moment it accepts the request?
- Is the file descriptor returned by u_connect and u_accept() same? (I couldn’t find it out because my ports are not opening)
- Can I use a random number as port since I am testing server client talk on the same computer?
I am using a wrapper library which contains the OS functions for socket programming.
Here is the code:
Server.c
int main()
{
char client[50];
char buf[1024];
u_port_t portnumber;
portnumber = 4862;
int fd = u_open(portnumber);
int communFd = u_accept(fd, client, 50);
printf("Opened com %d\n\n", communFd);
fprintf(stderr, "\nComun fd is %d\n\n\n", communFd);
read(communFd, buf, 1024);
write(STDOUT_FILENO, buf, 1024);
fprintf(stderr, "\n\nReading complete\n");
return 0;
}
Client.c
int main()
{
u_port_t portnumber;
portnumber = 4862;
char client[] = "Alfred";
char buf[1024];
int communFd = u_connect(portnumber, client);
printf("comun is %d\n", communFd);
read(STDIN_FILENO, buf, 1024);
write(communFd, buf, 1024);
return 0;
}
Server can read when the data sent by the client (via write()) is received and available into the socket read buffer.
No. Not even if server and client sides are running in the same process.
You can bind on a port from 0 to 65535.
The ones from 0 to 1024 are called
known portsand are already assigned to specific services byIANA. My suggestion is to use a port number in the range 49152-65535 but noone forbid you to use it a low value.If the port is bind by another process it will return an error code. Try with another one