I'm trying to set a default port number for when no port is entered in C socket programming. Does anyone know how I can do this? I keep getting segmentation fault on attempts.
Code:
#define PORT 12345
int main(int argc, char *argv[]) {
/* Thread and thread attributes */
pthread_t client_thread;
pthread_attr_t attr;
int sockfd, new_fd; /* listen on sock_fd, new connection on new_fd */
struct sockaddr_in my_addr; /* my address information */
struct sockaddr_in their_addr; /* connector's address information */
socklen_t sin_size;
int i=0;
/* Get port number for server to listen on */
if (argc != 2) {
fprintf(stderr,"usage: client port_number\n");
exit(1);
}
/* generate the socket */
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket");
exit(1);
}
/* generate the end point */
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(atoi(argv[1]));
my_addr.sin_addr.s_addr = INADDR_ANY;
I tried setting the default to 12345 when argc != 2, but I get segmentation fault. Any help would be appreciated!
You can use a conditional expression.
#define DEFAULT_PORT 12345
my_addr.sin_port = htons(argc < 2 ? DEFAULT_PORT : atoi(argv[1]));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.