I\'m writing a program to check to see if a port is open in C. One line in particular copies one of the arguments to a char array. However, when I try to compile, it says:
You've gotten a couple of answers that address exactly what you asked. My advice would be to step back and just eliminate that step, as it's completely unnecessary. I'd change these lines:
u_short port; /* user specified port number */
char addr[1023]; /* will be a copy of the address entered by u */
struct sockaddr_in address; /* the libc network address data structure */
port = atoi(argv[1]);
addr = strncpy(addr, argv[2], 1023);
bzero((char *)&address, sizeof(address)); /* init addr struct */
address.sin_addr.s_addr = inet_addr(addr); /* assign the address */
address.sin_port = htons(port); /* translate int2port num */
to something like this:
struct sockaddr_in address = {0};
address.sin_port = htons(atoi(argv[1]));
address.sin_addr.s_addr = inet_addr(argv[2]);
The existing code is doing a lot of unnecessary copying, making the code bigger and slower without accomplishing anything.
Edit: looking at it again, you should probably add a bit of error checking code (before what's above), something like:
if (argc != 3) {
fprintf(stderr, "Usage: %s ", argv[0]);
return EXIT_FAILURE;
}