Bonjour à tous,

Je travaille actuellement sur le Raspberry Pi en Python avec TKInter et socket. J'ai rédigé le programme ci-dessous qui permet de créer une connexion socket client/serveur sur un réseau TCP/IP. J'ai besoin d'un serveur qui puisse être connecté avec 4 clients sur 4 ports différents (10001, 10002, 10003 et 10004). Chaque client doit pouvoir envoyer, à tout moment, une commande au serveur. Pour cela, je lance 4 threads : un par client.

L'IHM TKInter permet de :
- Lancer les 4 threads avec le bouton "START"
- Afficher l'adresse IP locale avec le bouton "IP locale"
- Afficher l'adresse IP délivrée par le réseau avec le bouton "IP Reseau"
- Quitter l'IHM avec le bouton "Quitter"

Problème:

1) Si j'importe la librairie " from socket import * ":
- Les 4 threads se lancent normalement
- L'adresse IP locale s'affiche normalement
- MAIS l'adresse IP réseau ne s'affiche pas et j'obtient le message d'erreur suivant :
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 1470, in __call__
    return self.func(*args)
  File "C:\Users\Florian\Desktop\Code final.py", line 90, in get_lan_ip
    ip = socket.gethostbyname(socket.gethostname())
AttributeError: type object '_socketobject' has no attribute 'gethostbyname'
2) Si j'importe la librairie " import socket ":
- Les 4 threads ne se lancent pas et j'obtient le message d'erreur suivant :
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 1470, in __call__
    return self.func(*args)
  File "C:\Users\Florian\Desktop\Code final.py", line 108, in start_att
    serversock = socket(AF_INET, SOCK_STREAM)
NameError: global name 'AF_INET' is not defined
- L'adresse IP locale ne s'affiche pas et j'obtient le message d'erreur suivant :
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 1470, in __call__
    return self.func(*args)
  File "C:\Users\Florian\Desktop\Code final.py", line 77, in IP_local
    print gethostbyname(gethostname())
NameError: global name 'gethostbyname' is not defined
- MAIS l'adresse IP réseau s'affiche normalement


Je débute en python et je n'arrive pas à comprendre d'où vient ce problème.

Pourriez-vous m'aider ?
Merci d'avance

Voici mon code:

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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
#!/usr/bin/python
# -*- coding: cp1252 -*-
from socket import *
import os
import threading
import sys
from Tkinter import *
 
 
def server(host, port): #Fonction de gestion du serveur
 
    #def response(key):
     #   return 'echo: ' + key
 
    def handler(clientsock,addr): #Fonction de connexion socket avec 4 threads
        while 1:
            data = clientsock.recv(25) #25 bytes
            if not data: break         #out of the loop
 
            print data
 
            if data[0:4] == 'IDN?': #Gestion de l'IDN
                clientsock.send('IDN HHHHHH,625,R1,2\r\n')
 
            if data[0:4] == 'MOD?': #Gestion du Mode
                clientsock.send('MOD AUTO\r\n')
 
            if data[0:4] == 'STA?': #Gestion des données envoyées sur chaque port
                if port == 10001 :
                    sta = 'STA 0 935\r\n'
                if port == 10002 :
                    sta = 'STA 1 625\r\n'
                if port == 10003 :
                    sta = 'STA 2 400\r\n'
                if port == 10004 :
                    sta = 'STA 3 010\r\n'
                clientsock.send(sta)
 
            if data[0:2] == 'N?': #Gestion des 4 ports
                if port == 10001 :
                    name = 'NAM 0 WAY1\r\n'
                if port == 10002 :
                    name = 'NAM 1 WAY2\r\n'
                if port == 10003 :
                    name = 'NAM 2 WAY3\r\n'
                if port == 10004 :
                    name = 'NAM 3 WAY4\r\n'
                clientsock.send(name) 
 
            print repr (addr) + ' rx' + repr(data)
            #clientsock.send(response(data))
            #print repr(addr) + ' sent:' + repr(response(data))
            if "close" == data.rstrip(): break # out of the loop
 
        #came out of loop
        clientsock.close() #Déconnexion du client
        print addr, "- closed connection",port #log on console
        #thread_reopen(port)
 
    addr = (host, port)
    #create an AF_INET, STREAM socket (TCP) nammed 'serversock'
    serversock = socket(AF_INET, SOCK_STREAM)
    #Address Family : AF_INET (this is IP version 4 or IPv4)
    #Type : SOCK_STREAM (this means connection oriented TCP protocol)
    serversock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
    serversock.bind(addr)
    serversock.listen(1)
    while True:   #connect and re-connect
        clientsock, addr = serversock.accept() #serversock = socket(AF_INET, SOCK_STREAM)
        handler(clientsock, addr) #loop on 'handler' function
 
    #end def
#end def
 
 
def IP_local(): #Fonction qui renvoie l'adresse IP locale
    print gethostbyname(gethostname())
#end def
 
 
if os.name != "nt":
    import fcntl
    import struct
    def get_interface_ip(ifname):
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        return socket.inet_ntoa(fcntl.ioctl(s.fileno(),0x8915,struct.pack('256s', ifname[:15]))[20:24])
#end if
 
def get_lan_ip(): #Fonction qui renvoie l'adresse IP du reseau
    ip = socket.gethostbyname(socket.gethostname())
    if ip.startswith("127.") and os.name != "nt":
        interfaces = ["eth0","eth1","eth2","wlan0","wlan1","wifi0","ath0","ath1","ppp0"]
        for ifname in interfaces:
            try:
                ip = get_interface_ip(ifname)
                break
            except IOError:
                pass
    print ip
    return ip
#end def
 
 
if __name__=='__main__': #Programme principal
 
    def start_att(): #Fonction pour lancer les 4 threads
        import threading
        serversock = socket(AF_INET, SOCK_STREAM)
        HOST = '' #Symbolic name meaning all available interfaces
        PORTS = [10001,10002,10003,10004]
        threads = []
        for port in PORTS: #Create threads for each port
            th = threading.Thread(target=server, args=(HOST, port))
            th.start()
            threads.append(th)
            print th,port
 
 
#Création de l'IHM
fenetre = Tk()
fenetre.title("COMMANDE") #Fenêtre principale
 
Start = Button(fenetre,text="START",bg='yellow',command=start_att) #Bouton start pour lancer les 4 threads
Start.pack(side=TOP)
 
IP_L = Button(fenetre,text="IP Locale",bg='blue',command=IP_local) #Bouton pour récupérer l'adresse IP locale
IP_L.pack(side=TOP)
 
IP_R = Button(fenetre,text="IP Reseau",bg='blue',command=get_lan_ip) #Bouton pour récupérer l'adresse IP délivrée par le réseau TCP/IP
IP_R.pack(side=TOP)
 
quitButton = Button(fenetre,text="Quittter",bg='red',command=fenetre.destroy) #Bouton quitter
quitButton.pack(side=LEFT)
 
fenetre.mainloop() #Boucle principale