I'm trying to create a tcpServer and tcpClient messages terminal. i run into a problem with some code i can't get to work
I Follow aftr this guide here https://www.youtube.com/watch?v=BIJGSQEipEE
int newSocket = accept(sockfd, (struct sockaddr*)&newAddr, sizeof(newAddr));
printf("Connection accepted from %s:%d\n", inet_ntoa(newAddr.sin_addr), ntoa(newAddr.sin_port));
my error code is:
tcpServer.c:50:64: warning: incompatible integer to pointer conversion passing 'unsigned long' to parameter of type 'socklen_t *' (aka 'unsigned int *') [-Wint-conversion]
newSocket = accept(sockfd, (struct sockaddr*)&newAddr, sizeof(newAddr));
^~~~~~~~~~~~~~~
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/sys/socket.h:686:73: note: passing argument to parameter here
int accept(int, struct sockaddr * __restrict, socklen_t * __restrict)
^
tcpServer.c:54:81: warning: implicit declaration of function 'ntoa' is invalid in C99 [-Wimplicit-function-declaration]
printf("Connection accepted from %s:%d\n", inet_ntoa(newAddr.sin_addr), ntoa(newAddr.sin_port));
Why does error 2 come arise?
Thanks for helping me :)
The prototype of accept
is like:
int accept(int socket, struct sockaddr *restrict address, socklen_t *restrict address_len);
(from the Open Group Base Specification Issue 7)
The address_len
argument is a pointer to a socklen_t
object, not a numerical length.
Instead, you should create a variable of type socklen_t
to which you assign the size you're trying to pass:
socklen_t newAddrLength = sizeof(newAddr);
You can then pass a pointer to this variable in your call to accept
:
newSocket = accept(sockfd, (struct sockaddr*)&newAddr, &newAddrLength);
I'm unsure what you are trying to do with ntoa
. I believe the function that you'd want to use in its place is ntohs
, which converts the network-order of the sin_port
member to a host-order uint16_t
:
ntohs(newAddr.sin_port))
You'll then want to either cast this to a standard integer type, or use the PRIu16
format macro in <inttypes.h>
:
#include <inttypes.h>
printf("Connection accepted from %s:%" PRIu16 "\n", inet_ntoa(newAddr.sin_addr), ntohs(newAddr.sin_port));