Reputation: 11
I really don't know what I did wrong. I included all the good libraries. And tested it on my VPS and local Ubuntu installation. Also I looked up other code for the same program that do work. But I keep getting the "ERROR: could not bind internet address to the socket method" message. Here is my TCP server in C code:
#include <stdio.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netinet/in.h>
#include <stdlib.h>
//Enter The Port and the Ip Address here.
#define PORT 666
#define ADRESS 0
//Enter the amount of Maximum Poeple entering the server.
#define NUMBER_OF_CONNECTIONS 8
int main(){
int sockfd, newsockfd, portno = 666, clilen;
char message[1024];
struct sockaddr_in serv_addr, cli_addr;
int n;
sockfd = (AF_INET, SOCK_STREAM, 0);
if (sockfd < 0){
printf("ERROR: could not create server-socket.\n");
exit(1);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
// Declaring the port.
//portno = 666;
// Declaring the type of connection. (internet connection)
serv_addr.sin_family = AF_INET;
// Declaring the IP.
serv_addr.sin_addr.s_addr = INADDR_ANY;
// Declaring the Port.
serv_addr.sin_port = htons(portno);
// Binding the Socket?
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0){
printf("ERROR: could not bind internet address to the socket method.\n");
exit(1);
}
// Entering "Listen Mode".
listen(sockfd, NUMBER_OF_CONNECTIONS);
clilen = sizeof(cli_addr);
// Creating a New Socket for the client.
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < 0){
printf("ERROR: could not accept connection.\n");
exit(1);
}
//Clearing the message-buffer.
bzero(message,1024);
// Reading the message.
n = read(newsockfd,message,1023);
if (n < 0){
printf("ERROR: could not read message.\n");
}
printf("Message: %s\n",message);
n = write(newsockfd, "I got your message.", 18);
if (n < 0)
{
printf("ERROR: sending to client.\n");
}
return 0;
}
Upvotes: 0
Views: 1126
Reputation: 11
This helped me:
Ofcourse changing the sockfd = (AF_INET, SOCK_STREAM, 0);
to sockfd = socket(AF_INET, SOCK_STREAM, 0);
and for some reason I had to use root privileges for a port under 1024
.
Can someone maybe explain why?
Thank you for the help all :D
Upvotes: 0
Reputation: 18420
The problem is this line:
sockfd = (AF_INET, SOCK_STREAM, 0);
It is valid and the expression on the right side evaluates to 0
(see comma-operator in C).
Now the call to bind()
is placed on fd 0, which is usually a (pseudo-)terminal. This cannot succeed.
The solution is:
sockfd = socket(AF_INET, SOCK_STREAM, 0);
Upvotes: 4
Reputation: 3656
Try replacing:
sockfd = (AF_INET, SOCK_STREAM, 0);
with
sockfd = socket(AF_INET, SOCK_STREAM, 0);
Upvotes: 3