IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Réseau C Discussion :

Retour de valeur de la fonction connect (socket) en C


Sujet :

Réseau C

  1. #1
    Membre averti Avatar de Fooshi
    Homme Profil pro
    ICD
    Inscrit en
    Juin 2002
    Messages
    508
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : ICD
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Juin 2002
    Messages : 508
    Points : 364
    Points
    364
    Par défaut Retour de valeur de la fonction connect (socket) en C
    Bonjour,
    je suis en train de developper en client socket TCP en C et un serveur socket TCP en Python mon programme fonctionne trés bien. ils se connectent et se repondent MAIS bizarrerie de la nature , meme si ma fonction connect du client , se connecte bien au serveur, elle me renvoie -1 !

    je vous donne mon code de ma fonction connect :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    int
    net_socket_connect_tcp( int net_socket, const char * host, int numeric, const char * service )
    {
    	struct net_addr * net_addr = NULL;
    	int addr_count;
    	int test;
    	if (check(service != NULL, "Argument service is NULL"))
    	{
    		addr_count = net_addr_get_addrinfo(host, numeric, service, &net_addr);
    		if (check_not(addr_count == -1, "error form net_addr_get_addr_info"))
    		{
    			return -1;	
    		}
    		test = connect(net_socket,&net_addr->addr, net_addr->len);
    		fprintf(stdout,"%d",test);
     
    		if (test < 0)
    		{
    			trace_err("Can't connect to the server");
    		}
    		return 0;
    	}
    	return -1;
    }
    et ci joins le code du main du client qui initialise la socket, la bind, la connecte au serveur etc ...

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
     
     
    #include "common.h"
     
    static struct sys_events * sys_events;
     
    static void
    event_read_cb (struct sys_events * sys_events, struct sys_event * event );
     
    static struct sys_event_callback read_callback = { event_read_cb, 0 };
     
    int main ( int argc, char ** argv )
    {
    	int socket_index, socket_count = -1;
    	int * socket_array = NULL;
     
    	if (check_not(net_socket_initialize() != 0, "Can't initialize sockets"))	
    	{
    		return 1;
    	}
    	if (check_not(net_types_check_sizes() != 0, "Invalid types size"))			
    	{
    		return 1;
    	}
     
    	sys_events = sys_events_create(32);											
    	assert(sys_events != NULL, "");
     
    	socket_count = net_socket_bind_all_tcp(NULL, 1, "0", &socket_array);	
     
    	for (socket_index = 0; socket_index < socket_count; ++socket_index)
    	{
    		net_socket_connect_tcp(socket_array[socket_index], "127.0.0.1", 1, "9000");
    	}
     
    	for (socket_index = 0; socket_index < socket_count; ++socket_index)
    	{
    		sys_events_set_callback(sys_events, SYS_EVENT_READ, socket_array[socket_index], &read_callback);
    	}
     
    	while (sys_events_update(sys_events, SYS_EVENTS_INFINITE) == 0){}		
     
    	net_socket_close_all((unsigned int)(socket_count), socket_array);			
    	sys_events_delete(sys_events);											
    	net_socket_terminate();
    	return 0;		
    }
     
    void
    event_read_cb( struct sys_events * sys_events, struct sys_event * event )
    {
    	char send_msg[14] = "I'm the client";
    	unsigned int send_len = sizeof(send_msg);
    	char rcv_msg[256];	
    	unsigned int rcv_len = 256;
     
    	if (event->reason == SYS_EVENT_ERROR)
    	{
    		trace_err("SOCKET_ERROR");
    		return;
    	}	
    	if (net_socket_recv_tcp(event->ident,rcv_msg,&rcv_len) == NET_SOCKET_OK)
    	{
    		rcv_msg[rcv_len] = '\0';
    		trace_msg(rcv_msg);
    	}
    	else
    	{
    		trace_err("SOCKET RECV ERROR");
    	}
    	if (net_socket_send_tcp(event->ident,send_msg,send_len) != NET_SOCKET_OK)
    	{
    		trace_err("SOCKET SEND ERROR");
    	}
    }
    Quelqu'un aurais t'il une idée car je travaille sur un gros projet et j'aimerais faire du code vraiment propre

    Merci d'avance

  2. #2
    Membre averti Avatar de Fooshi
    Homme Profil pro
    ICD
    Inscrit en
    Juin 2002
    Messages
    508
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : ICD
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Juin 2002
    Messages : 508
    Points : 364
    Points
    364
    Par défaut
    J'ai testé un peu plus comme ceci :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
     
    if (connect(net_socket,&net_addr->addr, net_addr->len) == NET_SOCKET_ERROR)
    {
    	fprintf(stderr, "ligne %u - socket() - %s\n", __LINE__, sys_errlist[errno]);
    }
    code qui m'affiche qu'il n'y a aucune erreur.

  3. #3
    Modérateur
    Avatar de gangsoleil
    Homme Profil pro
    Manager / Cyber Sécurité
    Inscrit en
    Mai 2004
    Messages
    10 150
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Savoie (Rhône Alpes)

    Informations professionnelles :
    Activité : Manager / Cyber Sécurité

    Informations forums :
    Inscription : Mai 2004
    Messages : 10 150
    Points : 28 119
    Points
    28 119
    Par défaut
    Bonjour,

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
     
    if (connect(net_socket,&net_addr->addr, net_addr->len) == -1)
    {
    	fprintf(stderr, "ligne %u - socket() - errno : %d, %s\n", __LINE__, errno, strerror(errno) );
    }
    Est-ce que ce code te donne plus d'indications ?
    "La route est longue, mais le chemin est libre" -- https://framasoft.org/
    Les règles du forum

  4. #4
    Membre averti Avatar de Fooshi
    Homme Profil pro
    ICD
    Inscrit en
    Juin 2002
    Messages
    508
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : ICD
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Juin 2002
    Messages : 508
    Points : 364
    Points
    364
    Par défaut
    A peu pres la meme chose :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    ligne 353 - socket() - errno : 0, No error

  5. #5
    Modérateur
    Avatar de gangsoleil
    Homme Profil pro
    Manager / Cyber Sécurité
    Inscrit en
    Mai 2004
    Messages
    10 150
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Savoie (Rhône Alpes)

    Informations professionnelles :
    Activité : Manager / Cyber Sécurité

    Informations forums :
    Inscription : Mai 2004
    Messages : 10 150
    Points : 28 119
    Points
    28 119
    Par défaut
    Ok.

    Donc connect renvoit bien une erreur (code de retour -1), et ne positionne pas errno...

    C'est quoi ton OS ? Ca ne va probablement pas aider a trouver une solution, mais ca donnera toujours une idee.

    Normalement, si connect sort en erreur, tu ne dois pas continuer plus loin. Le soucis, c'est que la il a l'air de toujours sortir en erreur, ce qui ne t'aide pas a avancer.
    "La route est longue, mais le chemin est libre" -- https://framasoft.org/
    Les règles du forum

  6. #6
    Membre averti Avatar de Fooshi
    Homme Profil pro
    ICD
    Inscrit en
    Juin 2002
    Messages
    508
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : ICD
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Juin 2002
    Messages : 508
    Points : 364
    Points
    364
    Par défaut
    Je suis sur XP SP2, mon connect me renvoie -1 mais le socket se connecte bien au serveur !

  7. #7
    Modérateur
    Avatar de gangsoleil
    Homme Profil pro
    Manager / Cyber Sécurité
    Inscrit en
    Mai 2004
    Messages
    10 150
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Savoie (Rhône Alpes)

    Informations professionnelles :
    Activité : Manager / Cyber Sécurité

    Informations forums :
    Inscription : Mai 2004
    Messages : 10 150
    Points : 28 119
    Points
    28 119
    Par défaut
    hum...

    Peux-tu utiliser les sockets de l'API Windows ? A ma connaissance, la condition est de ne communiquer qu'entre machines sous Windows.

    Sinon, peut-etre voir dans le forum developpement windows si d'autres personnes ont deja parle de ce genre de probleme, mais je doute.
    "La route est longue, mais le chemin est libre" -- https://framasoft.org/
    Les règles du forum

  8. #8
    Membre averti Avatar de Fooshi
    Homme Profil pro
    ICD
    Inscrit en
    Juin 2002
    Messages
    508
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : ICD
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Juin 2002
    Messages : 508
    Points : 364
    Points
    364
    Par défaut
    Pour info j'initialise les sockets comme ca, le problème se trouve peu être ici :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    int
    net_socket_initialize ( void )
    {
    #if FREEAGE_TARGET == FREEAGE_TARGET_WINDOWS
    	WORD wVersionRequested;
    	WSADATA wsaData;
    #	if defined(FREEAGE_TARGET_WINDOWS_SERVER_2008)
    	wVersionRequested = MAKEWORD( 2, 2 );
    #	elif defined(FREEAGE_TARGET_WINDOWS_SERVER_2003)
    	wVersionRequested = MAKEWORD( 2, 0 );
    #	endif
    	if (check_not(WSAStartup(wVersionRequested, &wsaData) != 0, "Error from WSAStartup"))
    	{
    		return -1;
    	}
    #endif
    	return 0;
    }
    de plus j'ai mis a jour mon code :
    me fonction de connection :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    int
    net_socket_connect_tcp( int net_socket, const char * host, int numeric, const char * service )
    {
    	struct net_addr * net_addr = NULL;
    	int addr_count;
    	if (check(net_socket != -1, "Argument net_socket is invalid") &&
    		check(service != NULL, "Argument service is NULL"))
    	{
    		addr_count = net_addr_get_addrinfo(host, numeric, service, &net_addr, NET_ADDR_PROTOCOL_TCP);
    		if (check_not(addr_count == -1, "error form net_addr_get_addr_info"))
    		{
    			return -1;	
    		}
    		if (connect(net_socket,&net_addr->addr, net_addr->len) != NET_SOCKET_OK)
    		{
    			/* Actually, the function connect return -1 even if the current connection is made 
    			   The errno return No error */
    			fprintf(stderr, "ligne %u - socket() - errno : %d, %s\n", __LINE__, errno, strerror(errno) );
    		}		
    		return 0;
    	}
    	return -1;
    }
    Mon client C :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
     
    #include "common.h"
     
    static struct sys_events * sys_events;
     
    static void
    event_read_cb (struct sys_events * sys_events, struct sys_event * event );
     
    static struct sys_event_callback read_callback = { event_read_cb, 0 };
     
    int main ( int argc, char ** argv )
    {
    	int socket_index, socket_count = -1;
    	int * socket_array = NULL;
     
    	if (check_not(net_socket_initialize() != 0, "Can't initialize sockets"))	
    	{
    		return -1;
    	}
    	if (check_not(net_types_check_sizes() != 0, "Invalid types size"))			
    	{
    		return -1;
    	}
     
    	sys_events = sys_events_create(32);											
    	assert(sys_events != NULL, "");
     
    	socket_count = net_socket_bind_all(NULL, 1, "0", &socket_array, NET_ADDR_PROTOCOL_TCP);	
     
    	for (socket_index = 0; socket_index < socket_count; ++socket_index)
    	{
    		net_socket_connect_tcp(socket_array[socket_index], "127.0.0.1", 1, "9000");
    		sys_events_set_callback(sys_events, SYS_EVENT_READ, socket_array[socket_index], &read_callback);
    	}
     
    	while (sys_events_update(sys_events, SYS_EVENTS_INFINITE) == 0){}		
     
    	net_socket_close_all((unsigned int)(socket_count), socket_array);			
    	sys_events_delete(sys_events);											
    	net_socket_terminate();
    	return 0;		
    }
     
    void
    event_read_cb( struct sys_events * sys_events, struct sys_event * event )
    {
    	char send_msg[14] = "I'm the client";
    	unsigned int send_len = sizeof(send_msg);
    	char rcv_msg[256];	
    	unsigned int rcv_len = 256;
     
    	if (event->reason == SYS_EVENT_ERROR)
    	{
    		trace_err("SOCKET_ERROR");
    		return;
    	}	
    	if (net_socket_recv_tcp(event->ident,rcv_msg,&rcv_len) == NET_SOCKET_OK)
    	{
    		rcv_msg[rcv_len] = '\0';
    		trace_msg(rcv_msg);
    	}
    	else
    	{
    		trace_err("SOCKET RECV ERROR");
    	}
    	if (net_socket_send_tcp(event->ident,send_msg,send_len) != NET_SOCKET_OK)
    	{
    		trace_err("SOCKET SEND ERROR");
    	}
    }

  9. #9
    Membre averti Avatar de Fooshi
    Homme Profil pro
    ICD
    Inscrit en
    Juin 2002
    Messages
    508
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : ICD
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Juin 2002
    Messages : 508
    Points : 364
    Points
    364
    Par défaut Probleme de socket avec API Windows
    mon probleme vient t'il de l'initilialisation de ma socket ?
    je vous donne le code ci dessous sachant que pour le moment je lance mon serveur / client en local sous XP SP2.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    int
    net_socket_initialize ( void )
    {
    #if FREEAGE_TARGET == FREEAGE_TARGET_WINDOWS
    	WORD wVersionRequested;
    	WSADATA wsaData;
    #	if defined(FREEAGE_TARGET_WINDOWS_SERVER_2008)
    	wVersionRequested = MAKEWORD( 2, 2 );
    #	elif defined(FREEAGE_TARGET_WINDOWS_SERVER_2003)
    	wVersionRequested = MAKEWORD( 2, 0 );
    #	endif
    	if (check_not(WSAStartup(wVersionRequested, &wsaData) != 0, "Error from WSAStartup"))
    	{
    		return -1;
    	}
    #endif
    	return 0;
    }
    Merci d'avance car je bloque depuis un moment la dessus.

  10. #10
    Expert éminent
    Avatar de Melem
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Janvier 2006
    Messages
    3 656
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 38
    Localisation : France, Essonne (Île de France)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Électronique et micro-électronique

    Informations forums :
    Inscription : Janvier 2006
    Messages : 3 656
    Points : 8 389
    Points
    8 389
    Par défaut
    Windows n'utilise pas errno pour renseigner le programme sur l'origine d'une erreur de socket. C'est WSAGetLastError() ( = GetLastError()) qu'il faut appeler. Comment est défini check_not ?

  11. #11
    Membre averti Avatar de Fooshi
    Homme Profil pro
    ICD
    Inscrit en
    Juin 2002
    Messages
    508
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : ICD
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Juin 2002
    Messages : 508
    Points : 364
    Points
    364
    Par défaut
    check_not est défini avec une macro comme ceci :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
     
    /// The opposite of the check() macro.
    /** Example: if (check_not(ptr == NULL, "error !")) { return NULL; } */
    #define check_not(x,m)  (!(check(!(x),m)))
    check :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    /// This macro should be used to check an expression.
    /** Example: if (check(ptr != NULL, "error !")) { doit(ptr); }
     *  - If ptr is NULL, the check will call assert() in debug mode.
     *  - In release mode (NDEBUG is defined), this macro does nothing.
     *
     * WARNING: the result of the original expression is LOST, DO NOT USE 'x = check(expr)' unless you understand what you're doing.
     *
     * \param x An expression to check.
     * \param m A message to print if the expression is false.
     */
    #define check(x,m) (x)

    WSAGetLastError me renvoie un code d'erreur 10035

  12. #12
    Membre averti Avatar de Fooshi
    Homme Profil pro
    ICD
    Inscrit en
    Juin 2002
    Messages
    508
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : ICD
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Juin 2002
    Messages : 508
    Points : 364
    Points
    364
    Par défaut
    J'ai trouvé !

    Code erreur : WSAEWOULDBLOCK.

    Vu sur MSDN : Resource temporarily unavailable.

    "This error is returned from operations on nonblocking sockets that cannot be completed immediately, for example recv when no data is queued to be read from the socket. It is a nonfatal error, and the operation should be retried later. It is normal for WSAEWOULDBLOCK to be reported as the result from calling connect on a nonblocking SOCK_STREAM socket, since some time must elapse for the connection to be established."

    Ma socket est non bloquante en mode connecté.

  13. #13
    Modérateur
    Avatar de gangsoleil
    Homme Profil pro
    Manager / Cyber Sécurité
    Inscrit en
    Mai 2004
    Messages
    10 150
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Savoie (Rhône Alpes)

    Informations professionnelles :
    Activité : Manager / Cyber Sécurité

    Informations forums :
    Inscription : Mai 2004
    Messages : 10 150
    Points : 28 119
    Points
    28 119
    Par défaut
    Ok, j'avoue, je suis fan du "On retourne une erreur car tout se passe bien."

    Pourtant, je le savais qu'ils avaient un code d'erreur ERROR_SUCCESS. Ça aurait du me mettre la puce a l'oreille. Mais de la à faire ca...

    Extrait de msi.h :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    //
    // MessageId: ERROR_SUCCESS
    //
    // MessageText:
    //
    //  The operation completed successfully.
    //
    #define ERROR_SUCCESS                    0L
    "La route est longue, mais le chemin est libre" -- https://framasoft.org/
    Les règles du forum

  14. #14
    Membre actif Avatar de ironzorg
    Profil pro
    Inscrit en
    Juillet 2006
    Messages
    288
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juillet 2006
    Messages : 288
    Points : 245
    Points
    245
    Par défaut
    Chaque fois que quelqu'un a essaye d'utiliser du code UN*X sous windows ca s'est mal passe :p

    Bizarrerie tout de meme, es tu sur que personne n'a reporte ce cas de figure auparavant ? Bon a savoir.

  15. #15
    Membre averti Avatar de Fooshi
    Homme Profil pro
    ICD
    Inscrit en
    Juin 2002
    Messages
    508
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : ICD
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Juin 2002
    Messages : 508
    Points : 364
    Points
    364
    Par défaut
    @Ironzorg : En cherchant bien, il me semble que personne n'ai rapporté ce cas de figure auparavant.

Discussions similaires

  1. Fonction connect socket TCP/IP
    Par Signal40 dans le forum C
    Réponses: 6
    Dernier message: 23/01/2013, 13h49
  2. Retour de valeur d'une fonction
    Par guigouz dans le forum SQL
    Réponses: 5
    Dernier message: 10/06/2008, 15h21
  3. Réponses: 23
    Dernier message: 28/05/2008, 17h53
  4. [Tableaux] Retour de valeur d'une fonction
    Par Trebor_ dans le forum Langage
    Réponses: 5
    Dernier message: 10/03/2008, 14h24
  5. [Mail] Retour de valeur d'une fonction
    Par pat06 dans le forum Langage
    Réponses: 3
    Dernier message: 14/12/2007, 11h32

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo