获取TCP / IP地址,而不是localhost

时间:2014-06-03 12:53:21

标签: java tcp chat

我在Barry Boone和William R Stanek撰写的Java 2:Exam Guide一书中找到了这段代码。 这段代码给了我内部IP 127.0.0.1 但我想要像115.245.12.61这样的东西。 我怎么能得到这个。 我在下面提供我的代码

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;

public class SingleChat extends Panel {
    Socket sock;
    TextArea ta_RecText;
    private GridBagConstraints c;
    private GridBagLayout gridBag;
    private Frame frame;
    private Label label;
    public int port = 5001;
    private TextField tf_Send;
    private DataOutputStream remoteOut;
    static String szUserName = "";

    public static void main (String [] args){
        final Frame f = new Frame("Waiting For Connection...");
        String s = null;
        Color fore , back;
        fore = new java.awt.Color(255, 255, 255);
        back = new java.awt.Color(0, 173, 232);
        if (args.length > 0)
            s = args[0];
        SingleChat chat = new SingleChat(f);
        Panel pane = new Panel(), butPane = new Panel();
        Label l_Label = new Label("//RADconnect");
        l_Label.setForeground(fore);
        l_Label.setBackground(back);
        l_Label.setFont(new java.awt.Font("Lucida Console", 0, 24));
        pane.add(l_Label);
        f.setForeground(fore);
        f.setBackground(back);
        f.add("North", pane);
        f.add("Center", chat);
        Button but = new Button("EXIT");
        but.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(ActionEvent e) {
                f.dispose();
                System.exit(0);
            }
        });
        but.setBackground(fore);
        but.setForeground(back);
        butPane.add(but);
        f.add("South", butPane);
        f.setSize(450, 350);
        f.show();
        if (s == null){
            chat.server();
        }
        else{
            chat.client(s);
        }
    }

    public SingleChat (Frame f){
        frame = f;
        frame.addWindowListener(new WindowExitHandler());
        Insets insets = new Insets (10, 20, 5, 10);
        gridBag = new GridBagLayout();
        setLayout(gridBag);
        c = new GridBagConstraints();
        c.insets = insets;
        c.gridx = 0;
        c.gridx = 0;
        label = new Label("Text To Send:");
        gridBag.setConstraints(label, c);
        add(label);
        c.gridx = 1;
        tf_Send = new TextField(40);
        tf_Send.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try{
                    //Intercept Messages And Send Them
                    String msg = tf_Send.getText();
                    remoteOut.writeUTF(szUserName+": "+msg);
                    tf_Send.setText("");
                    ta_RecText.append(szUserName+": "+msg+"\n");
                } catch (IOException x) {
                    displayMsg(x.getMessage()+": Connection to Peer Lost");
                }
            }
        });
        gridBag.setConstraints(tf_Send, c);
        add(tf_Send);
        c.gridy = 1;
        c.gridx = 0;
        label = new Label("Text Recived:");
        gridBag.setConstraints(label, c);
        add(label);
        c.gridx = 1;
        ta_RecText = new TextArea(5, 40);
        gridBag.setConstraints(ta_RecText, c);
        add(ta_RecText);
        ta_RecText.setForeground(Color.BLACK);
        tf_Send.setForeground(Color.BLACK);
    }

    private void server(){
        ServerSocket sv_Sock = null;
        try {
            InetAddress sv_Addr = InetAddress.getByName(null);
            displayMsg("Waiting For Connection on "+sv_Addr.getHostAddress()+":"+port);
            sv_Sock = new ServerSocket(port, 1);
            sock = sv_Sock.accept();
            displayMsg("Accepted Connection From "+sock.getInetAddress().getHostName());
            remoteOut = new DataOutputStream(sock.getOutputStream());
            new SingleChatRecive(this).start();
        } catch (IOException x){
            displayMsg(x.getMessage()+": Falied to connect to client");
        }
        finally {
            if (sv_Sock != null){
                try{
                    sv_Sock.close();
                } catch (IOException x){
                }
            }
        }
    }
    private void client(String sv_Name){
        try {
            if (sv_Name.equals("local")){
                sv_Name = null;
            }
            InetAddress sv_Addr = InetAddress.getByName(sv_Name);
            sock = new Socket(sv_Addr.getHostName(), port);
            remoteOut = new DataOutputStream(sock.getOutputStream());
             displayMsg("Connected to Server "+sv_Addr.getHostName()+":"+sock.getPort());
             new SingleChatRecive(this).start();
        } catch (IOException e){
            displayMsg(e.getMessage()+": Failed to connect to server");
        }
    }
    void displayMsg(String sz_Title){
        frame.setTitle(sz_Title);
    }
    protected void finalize() throws Throwable {
        try {
            if (remoteOut != null){
                remoteOut.close();
            }
            if (sock != null){
                sock.close();
            }
        } catch (IOException e){
        }
        super.finalize();
    }
    class WindowExitHandler extends WindowAdapter{
        public void windowClosing(WindowEvent e){
            Window w = e.getWindow();
            w.setVisible(false);
            w.dispose();
            System.exit(0);
        }
    }
    void saveData(){

    }
}

class SingleChatRecive extends Thread {
    private SingleChat chat;
    private DataInputStream remoteIn;
    private boolean listening = true;
    public SingleChatRecive(SingleChat chat){
        this.chat = chat;
    }
    public synchronized void run(){
        String s;
        try {
            remoteIn = new DataInputStream(chat.sock.getInputStream());
            while (listening) {
                s = remoteIn.readUTF();
                chat.ta_RecText.append(s+"\n");
            }
        } catch (IOException e){
            chat.displayMsg(e.getMessage()+": Connection to Peer Lost!");
        } finally {
            try {
                if (remoteIn != null) {
                    remoteIn.close();
                }
            } catch (IOException e){
            }
        }
    }
}

可以做些什么更改以避免获得127.0.0.1 致谢

1 个答案:

答案 0 :(得分:1)

从你的代码:

InetAddress sv_Addr = InetAddress.getByName(null);

javadoc:“如果主机为空,则返回表示环回接口地址的InetAddress。”

环回接口的IP地址为127.0.0.1

要获取其他IP地址,您必须使用有效的主机名交换null。如果您正在运行服务器,那么您的本地计算机名称可以执行,但任何有效的主机名都应该有效。

InetAddress sv_Addr = InetAddress.getByName("myserver.mydomain.com");