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

avec Java Discussion :

Port Forwarding avec WaifUPnP


Sujet :

avec Java

  1. #1
    Membre habitué Avatar de Pecose
    Homme Profil pro
    Batiment
    Inscrit en
    Février 2013
    Messages
    310
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 37
    Localisation : France, Alpes Maritimes (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Batiment
    Secteur : Bâtiment

    Informations forums :
    Inscription : Février 2013
    Messages : 310
    Points : 194
    Points
    194
    Par défaut Port Forwarding avec WaifUPnP
    Bonjour tout le monde,

    J'ai essayé WaifUPnP mais je rencontre un petit problème.
    Voilà l'erreur que je rencontre:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    java.net.SocketTimeoutException: Receive timed out
    java.net.SocketTimeoutException: Receive timed out
    java.net.SocketTimeoutException: Receive timed out
    C'est pas très riche en informations du coup je vous donne le code en entier:

    -Déjà, j'ai trouver la source du problème avec un tas de sysout:
    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
    @Override
            public void run() {
                try {
                    byte[] req = this.req.getBytes();
                    DatagramSocket s = new DatagramSocket(new InetSocketAddress(ip, 0));
                    s.send(new DatagramPacket(req, req.length, new InetSocketAddress("239.255.255.250", 1900)));
                    s.setSoTimeout(3000);
                    for(;;) {
                    	DatagramPacket recv = new DatagramPacket(new byte[1536], 1536);
                        s.receive(recv);//Problème ici!!!!!!!!!
                        Gateway gw = new Gateway(recv.getData(), ip);
                        gatewayFound(gw);
                    }
                }catch (Exception e) { System.err.println(e); }
            }
    Voila la classe en entier:
    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
    /*
     * Copyright (C) 2015 Federico Dossena (adolfintel.com).
     *
     * This library is free software; you can redistribute it and/or
     * modify it under the terms of the GNU Lesser General Public
     * License as published by the Free Software Foundation; either
     * version 2.1 of the License, or (at your option) any later version.
     *
     * This library is distributed in the hope that it will be useful,
     * but WITHOUT ANY WARRANTY; without even the implied warranty of
     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     * Lesser General Public License for more details.
     *
     * You should have received a copy of the GNU Lesser General Public
     * License along with this library; if not, write to the Free Software
     * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
     * MA 02110-1301  USA
     */
    package waifUPNP;
     
    import java.io.IOException;
    import java.net.DatagramPacket;
    import java.net.DatagramSocket;
    import java.net.Inet4Address;
    import java.net.InetAddress;
    import java.net.InetSocketAddress;
    import java.net.NetworkInterface;
    import java.net.SocketTimeoutException;
    import java.util.Enumeration;
    import java.util.LinkedList;
     
    /**
     * @author Federico
     */
    abstract class GatewayFinder {
     
        private static final String[] SEARCH_MESSAGES;
     
        static {
            LinkedList<String> m = new LinkedList<String>();
            for (String type : new String[]{"urn:schemas-upnp-org:device:InternetGatewayDevice:1", "urn:schemas-upnp-org:service:WANIPConnection:1", "urn:schemas-upnp-org:service:WANPPPConnection:1"}) {
                m.add("M-SEARCH * HTTP/1.1\r\nHOST: 239.255.255.250:1900\r\nST: " + type + "\r\nMAN: \"ssdp:discover\"\r\nMX: 2\r\n\r\n");
            }
            SEARCH_MESSAGES = m.toArray(new String[]{});
        }
     
        private class GatewayListener extends Thread {
     
            private InetAddress ip;
            private String req;
     
            public GatewayListener(InetAddress ip, String req) {
                setName("WaifUPnP - Gateway Listener");
                this.ip = ip;
                this.req = req;
            }
     
            @SuppressWarnings("resource")
    		@Override
            public void run() {
                try {
                    byte[] req = this.req.getBytes();
                    DatagramSocket s = new DatagramSocket(new InetSocketAddress(ip, 0));
                    s.send(new DatagramPacket(req, req.length, new InetSocketAddress("239.255.255.250", 1900)));
                    s.setSoTimeout(3000);
                    for(;;) {
                    	DatagramPacket recv = new DatagramPacket(new byte[1536], 1536);
                        s.receive(recv);//Problème ici!!!!!!!!!
                        Gateway gw = new Gateway(recv.getData(), ip);
                        gatewayFound(gw);
                    }
                }catch (Exception e) { System.err.println(e); }
            }
        }
     
        private LinkedList<GatewayListener> listeners = new LinkedList<GatewayListener>();
     
        public GatewayFinder() {
            for (Inet4Address ip : getLocalIPs()) {
                for (String req : SEARCH_MESSAGES) {
                    GatewayListener l = new GatewayListener(ip, req);
                    l.start();
                    listeners.add(l);
                }
            }
        }
     
        public boolean isSearching() {
            for (GatewayListener l : listeners) {
                if (l.isAlive()) {
                    return true;
                }
            }
            return false;
        }
     
        public abstract void gatewayFound(Gateway g);
     
        private static Inet4Address[] getLocalIPs() {
            LinkedList<Inet4Address> ret = new LinkedList<Inet4Address>();
            try {
                Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces();
                while (ifaces.hasMoreElements()) {
                    try {
                        NetworkInterface iface = ifaces.nextElement();
                        if (!iface.isUp() || iface.isLoopback() || iface.isVirtual() || iface.isPointToPoint()) {
                            continue;
                        }
                        Enumeration<InetAddress> addrs = iface.getInetAddresses();
                        if (addrs == null) {
                            continue;
                        }
                        while (addrs.hasMoreElements()) {
                            InetAddress addr = addrs.nextElement();
                            if (addr instanceof Inet4Address) {
                                ret.add((Inet4Address) addr);
                            }
                        }
                    } catch (Throwable t) {
                    }
                }
            } catch (Throwable t) {
            }
            return ret.toArray(new Inet4Address[]{});
        }
     
    }
    Moi je fait simplement:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    UPnP.openPortTCP(port);
    Voila la classe UPnP:
    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
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    /*Copyright (C) 2015 Federico Dossena (adolfintel.com).
     *
     * This library is free software; you can redistribute it and/or
     * modify it under the terms of the GNU Lesser General Public
     * License as published by the Free Software Foundation; either
     * version 2.1 of the License, or (at your option) any later version.
     *
     * This library is distributed in the hope that it will be useful,
     * but WITHOUT ANY WARRANTY; without even the implied warranty of
     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     * Lesser General Public License for more details.
     *
     * You should have received a copy of the GNU Lesser General Public
     * License along with this library; if not, write to the Free Software
     * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
     * MA 02110-1301  USA
     */
     
    package waifUPNP;
     
    /**
     * This class contains static methods that allow quick access to UPnP Port Mapping.<br>
     * Commands will be sent to the default gateway.
     * 
     * @author Federico
     */
    public class UPnP {
     
        private static Gateway defaultGW = null;
        private static final GatewayFinder finder = new GatewayFinder() {
            @Override
            public void gatewayFound(Gateway g) {
                synchronized (finder) {
                    if (defaultGW == null) {
                        defaultGW = g;
                    }
                }
            }
        };
     
        /**
         * Waits for UPnP to be initialized (takes ~3 seconds).<br>
         * It is not necessary to call this method manually before using UPnP functions
         */
        public static void waitInit() {
            while (finder.isSearching()) {
                try {
                    Thread.sleep(1);
                } catch (InterruptedException ex) {
                }
            }
        }
     
        /**
         * Is there an UPnP gateway?<br>
         * This method is blocking if UPnP is still initializing<br>
         * All UPnP commands will fail if UPnP is not available
         * 
         * @return true if available, false if not
         */
        public static boolean isUPnPAvailable(){
            waitInit();
            return defaultGW!=null;
        }
     
        /**
         * Opens a TCP port on the gateway
         * 
         * @param port TCP port (0-65535)
         * @return true if the operation was successful, false otherwise
         */
        public static boolean openPortTCP(int port) {
            if(!isUPnPAvailable()) return false;
            return defaultGW.openPort(port, false);
        }
     
        /**
         * Opens a UDP port on the gateway
         * 
         * @param port UDP port (0-65535)
         * @return true if the operation was successful, false otherwise
         */
        public static boolean openPortUDP(int port) {
            if(!isUPnPAvailable()) return false;
            return defaultGW.openPort(port, true);
        }
     
        /**
         * Closes a TCP port on the gateway<br>
         * Most gateways seem to refuse to do this
         * 
         * @param port TCP port (0-65535)
         * @return true if the operation was successful, false otherwise
         */
        public static boolean closePortTCP(int port) {
            if(!isUPnPAvailable()) return false;
            return defaultGW.closePort(port, false);
        }
     
        /**
         * Closes a UDP port on the gateway<br>
         * Most gateways seem to refuse to do this
         * 
         * @param port UDP port (0-65535)
         * @return true if the operation was successful, false otherwise
         */
        public static boolean closePortUDP(int port) {
            if(!isUPnPAvailable()) return false;
            return defaultGW.closePort(port, true);
        }
     
        /**
         * Checks if a TCP port is mapped<br>
         * 
         * @param port TCP port (0-65535)
         * @return true if the port is mapped, false otherwise
         */
        public static boolean isMappedTCP(int port) {
            if(!isUPnPAvailable()) return false;
            return defaultGW.isMapped(port, false);
        }
     
        /**
         * Checks if a UDP port is mapped<br>
         * 
         * @param port UDP port (0-65535)
         * @return true if the port is mapped, false otherwise
         */
        public static boolean isMappedUDP(int port) {
            if(!isUPnPAvailable()) return false;
            return defaultGW.isMapped(port, false);
        }
     
        /**
         * Gets the external IP address of the default gateway
         * 
         * @return external IP address as string, or null if not available
         */
        public static String getExternalIP(){
            if(!isUPnPAvailable()) return null;
            return defaultGW.getExternalIP();
        }
     
        /**
         * Gets the internal IP address of this machine
         * 
         * @return internal IP address as string, or null if not available
         */
        public static String getLocalIP(){
            if(!isUPnPAvailable()) return null;
            return defaultGW.getLocalIP();
        }
     
    }
    Et la dernière classe:
    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
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    /*
     * Copyright (C) 2015 Federico Dossena (adolfintel.com).
     *
     * This library is free software; you can redistribute it and/or
     * modify it under the terms of the GNU Lesser General Public
     * License as published by the Free Software Foundation; either
     * version 2.1 of the License, or (at your option) any later version.
     *
     * This library is distributed in the hope that it will be useful,
     * but WITHOUT ANY WARRANTY; without even the implied warranty of
     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     * Lesser General Public License for more details.
     *
     * You should have received a copy of the GNU Lesser General Public
     * License along with this library; if not, write to the Free Software
     * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
     * MA 02110-1301  USA
     */
    package waifUPNP;
     
    import java.net.HttpURLConnection;
    import java.net.InetAddress;
    import java.net.URL;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.StringTokenizer;
    import javax.xml.parsers.DocumentBuilderFactory;
    import org.w3c.dom.Document;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.w3c.dom.traversal.DocumentTraversal;
    import org.w3c.dom.traversal.NodeFilter;
    import org.w3c.dom.traversal.NodeIterator;
     
    /**
     * @author Federico
     */
    class Gateway {
     
        private InetAddress iface;
     
        private String serviceType = null, controlURL = null;
     
        public Gateway(byte[] data, InetAddress ip) throws Exception {
            this.iface = ip;
            String location = null;
            StringTokenizer st = new StringTokenizer(new String(data), "\n");
     
     
            while (st.hasMoreTokens()) {
                String s = st.nextToken().trim();
                if (s.isEmpty() || s.startsWith("HTTP/1.") || s.startsWith("NOTIFY *")) {
                    continue;
                }
                String name = s.substring(0, s.indexOf(':')), val = s.length() >= name.length() ? s.substring(name.length() + 1).trim() : null;
                if (name.equalsIgnoreCase("location")) {
                    location = val;
                }
            }
            if (location == null) { throw new Exception("Unsupported Gateway"); }
     
            Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(location);
            NodeList services = d.getElementsByTagName("service");
     
            for (int i = 0; i < services.getLength(); i++) {
                Node service = services.item(i);
                NodeList n = service.getChildNodes();
                String serviceType = null, controlURL = null;
                for (int j = 0; j < n.getLength(); j++) {
                    Node x = n.item(j);
                    if (x.getNodeName().trim().equalsIgnoreCase("serviceType")) {
                        serviceType = x.getFirstChild().getNodeValue();
                    } else if (x.getNodeName().trim().equalsIgnoreCase("controlURL")) {
                        controlURL = x.getFirstChild().getNodeValue();
                    }
                }
                if (serviceType == null || controlURL == null) {
                    continue;
                }
                if (serviceType.trim().toLowerCase().contains(":wanipconnection:") || serviceType.trim().toLowerCase().contains(":wanpppconnection:")) {
                    this.serviceType = serviceType.trim();
                    this.controlURL = controlURL.trim();
                }
            }
            if (controlURL == null) {
                throw new Exception("Unsupported Gateway");
            }
            int slash = location.indexOf("/", 7); //finds first slash after http://
            if (slash == -1) {
                throw new Exception("Unsupported Gateway");
            }
            location = location.substring(0, slash);
            if (!controlURL.startsWith("/")) {
                controlURL = "/" + controlURL;
            }
            controlURL = location + controlURL;
        }
     
        private Map<String, String> command(String action, Map<String, String> params) throws Exception {
            Map<String, String> ret = new HashMap<String, String>();
            String soap = "<?xml version=\"1.0\"?>\r\n" + "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
                    + "<SOAP-ENV:Body>"
                    + "<m:" + action + " xmlns:m=\"" + serviceType + "\">";
            if (params != null) {
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    soap += "<" + entry.getKey() + ">" + entry.getValue() + "</" + entry.getKey() + ">";
                }
            }
            soap += "</m:" + action + "></SOAP-ENV:Body></SOAP-ENV:Envelope>";
            byte[] req = soap.getBytes();
            HttpURLConnection conn = (HttpURLConnection) new URL(controlURL).openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-Type", "text/xml");
            conn.setRequestProperty("SOAPAction", "\"" + serviceType + "#" + action + "\"");
            conn.setRequestProperty("Connection", "Close");
            conn.setRequestProperty("Content-Length", "" + req.length);
            conn.getOutputStream().write(req);
            Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(conn.getInputStream());
            NodeIterator iter = ((DocumentTraversal) d).createNodeIterator(d.getDocumentElement(), NodeFilter.SHOW_ELEMENT, null, true);
            Node n;
            while ((n = iter.nextNode()) != null) {
                try {
                    if (n.getFirstChild().getNodeType() == Node.TEXT_NODE) {
                        ret.put(n.getNodeName(), n.getTextContent());
                    }
                } catch (Throwable t) {
                }
            }
            conn.disconnect();
            return ret;
        }
     
        public String getLocalIP() {
            return iface.getHostAddress();
        }
     
        public String getExternalIP() {
            try {
                Map<String, String> r = command("GetExternalIPAddress", null);
                return r.get("NewExternalIPAddress");
            } catch (Throwable t) {
                return null;
            }
        }
     
        public boolean openPort(int port, boolean udp) {
            if (port < 0 || port > 65535) {
                throw new IllegalArgumentException("Invalid port");
            }
            Map<String, String> params = new HashMap<String, String>();
            params.put("NewRemoteHost", "");
            params.put("NewProtocol", udp ? "UDP" : "TCP");
            params.put("NewInternalClient", iface.getHostAddress());
            params.put("NewExternalPort", "" + port);
            params.put("NewInternalPort", "" + port);
            params.put("NewEnabled", "1");
            params.put("NewPortMappingDescription", "WaifUPnP");
            params.put("NewLeaseDuration", "0");
            try {
                Map<String, String> r = command("AddPortMapping", params);
                return r.get("errorCode") == null;
            } catch (Exception ex) {
                return false;
            }
        }
     
        public boolean closePort(int port, boolean udp) {
            if (port < 0 || port > 65535) {
                throw new IllegalArgumentException("Invalid port");
            }
            Map<String, String> params = new HashMap<String, String>();
            params.put("NewRemoteHost", "");
            params.put("NewProtocol", udp ? "UDP" : "TCP");
            params.put("NewExternalPort", "" + port);
            try {
                command("DeletePortMapping", params);
                return true;
            } catch (Exception ex) {
                return false;
            }
        }
     
        public boolean isMapped(int port, boolean udp) {
            if (port < 0 || port > 65535) {
                throw new IllegalArgumentException("Invalid port");
            }
            Map<String, String> params = new HashMap<String, String>();
            params.put("NewRemoteHost", "");
            params.put("NewProtocol", udp ? "UDP" : "TCP");
            params.put("NewExternalPort", "" + port);
            try {
                Map<String, String> r = command("GetSpecificPortMappingEntry", params);
                if (r.get("errorCode") != null) {
                    throw new Exception();
                }
                return r.get("NewInternalPort") != null;
            } catch (Exception ex) {
                return false;
            }
     
        }
     
    }
    Merci de votre aide.
    Des jours c'est facile, des jours c'est pas facile, mais c'est jamais le même jour.

  2. #2
    Membre habitué Avatar de Pecose
    Homme Profil pro
    Batiment
    Inscrit en
    Février 2013
    Messages
    310
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 37
    Localisation : France, Alpes Maritimes (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Batiment
    Secteur : Bâtiment

    Informations forums :
    Inscription : Février 2013
    Messages : 310
    Points : 194
    Points
    194
    Par défaut
    Il y a des chances que ça ne vienne pas du code mais si c'est un problème de réseau je ne sais pas du tout par ou commencer.
    Une idée?
    Des jours c'est facile, des jours c'est pas facile, mais c'est jamais le même jour.

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Port forwarding et port triggering
    Par kap dans le forum Développement
    Réponses: 4
    Dernier message: 25/10/2005, 12h28
  2. Comment écouter un port série avec flash ?
    Par Alex01 dans le forum Flash
    Réponses: 11
    Dernier message: 07/10/2005, 16h11
  3. [MFC] Acquisition du port midi avec visual c++ 6.0
    Par spirit_1999 dans le forum MFC
    Réponses: 2
    Dernier message: 16/05/2005, 19h26
  4. port 80 avec Apache
    Par SuperDog dans le forum Apache
    Réponses: 5
    Dernier message: 08/07/2004, 17h28
  5. Ports forwarding avec iptables
    Par Iced Earth dans le forum Réseau
    Réponses: 6
    Dernier message: 19/11/2002, 21h24

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