Dans le cas d'une adresse IP et d'un port, vous n'avez pas besoin de dupliquer les chaînes. Il suffit de les analyser et de stocker les valeurs dans un sockaddr.
#include <arpa/inet.h> // for inet_ntop, inet_pton
#include <getopt.h> // for getopt, optarg
#include <netinet/in.h> // for sockaddr_in, etc
#include <stdio.h> // for fprintf, printf, stderr
#include <stdlib.h> // for atoi, EXIT_SUCCESS
#include <string.h> // for memset
#include <sys/socket.h> // for AF_INET
int main(int argc, char *argv[])
{
struct sockaddr_in sa;
char c;
memset(&sa, 0, sizeof(sa));
sa.sin_family = AF_INET;
sa.sin_addr.s_addr = INADDR_ANY;
sa.sin_port = 0;
while ((c = getopt(argc, argv, "i:p:")) != -1)
{
switch (c)
{
case 'p':
sa.sin_port = htons(atoi(optarg));
break;
case 'i':
inet_pton(AF_INET, optarg, &(sa.sin_addr));
break;
case '?':
fprintf(stderr, "Unknown option\n");
break;
} /* ----- end switch ----- */
}
char str[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &(sa.sin_addr), str, INET_ADDRSTRLEN);
printf("%s:%d\n", str, ntohs(sa.sin_port));
return EXIT_SUCCESS;
} /* ---------- end of function main ---------- */
La réponse à l'aide de strdup est une meilleure solution à ce problème. Il évite de créer un tampon de taille fixe pour une chaîne de longueur inconnue – tvanfosson