简体   繁体   中英

How to know the IP from hostname of the server using sockets

I am making an android application using sokets where the client sends a message to the server. At this moment the client sends a message from the data that I put in editText (ip and port number). Is it possible to know the ip of the server without being manually, for example if the client knew the name of the server would know your ip using DNS ... So the client could send a message to the server without having to search the ip automatically. Can anyone help me?

Here is the code from the client:

        public class MainActivity extends Activity {
            TextView textResponse;
            EditText editTextAddress, editTextPort;
            Button buttonConnect, buttonClear;
            EditText welcomeMsg;

            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);

                editTextAddress = (EditText) findViewById(R.id.address);
                editTextPort = (EditText) findViewById(R.id.port);
                buttonConnect = (Button) findViewById(R.id.connect);
                buttonClear = (Button) findViewById(R.id.clear);
                textResponse = (TextView) findViewById(R.id.response);
                welcomeMsg = (EditText)findViewById(R.id.welcomemsg);
                buttonConnect.setOnClickListener(buttonConnectOnClickListener);

                buttonClear.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        textResponse.setText("");
                    }
                });
            }

            View.OnClickListener buttonConnectOnClickListener = new View.OnClickListener() {

                @Override
                public void onClick(View arg0) {

                    String tMsg = welcomeMsg.getText().toString();
                    if(tMsg.equals("")){
                        tMsg = null;
                        Toast.makeText(MainActivity.this, "No Welcome Msg sent", Toast.LENGTH_SHORT).show();
                    }
        //Search ip and editText port number
                    MyClientTask myClientTask = new MyClientTask(editTextAddress.getText().toString(), Integer.parseInt(editTextPort.getText().toString()),
                            tMsg);
                    myClientTask.execute();
                }
            };

            public class MyClientTask extends AsyncTask<Void, Void, Void> {

                String dstAddress;
                int dstPort;
                String response = "";
                String msgToServer;

                MyClientTask(String addr, int port, String msgTo) {
                    dstAddress = addr;
                    dstPort = port;
                    msgToServer = msgTo;
                }

                @Override
                protected Void doInBackground(Void... arg0) {

                    Socket socket = null;
                    DataOutputStream dataOutputStream = null;
                    DataInputStream dataInputStream = null;

                    try {
        //create the conection  between the client and the server using the ip and port number
                        socket = new Socket(dstAddress, dstPort);
                        dataOutputStream = new DataOutputStream(
                                socket.getOutputStream());
                        dataInputStream = new DataInputStream(socket.getInputStream());

    //send message to the server
                        if(msgToServer != null){
                            dataOutputStream.writeUTF(msgToServer);
                        }

                        response = dataInputStream.readUTF();

                    } catch (UnknownHostException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        response = "UnknownHostException: " + e.toString();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        response = "IOException: " + e.toString();
                    } finally {
                        if (socket != null) {
                            try {
//close the conection
                                socket.close();
                            } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }

                        if (dataOutputStream != null) {
                            try {
                                dataOutputStream.close();
                            } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }

                        if (dataInputStream != null) {
                            try {
                                dataInputStream.close();
                            } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                    }
                    return null;
                }

                @Override
                protected void onPostExecute(Void result) {
                    textResponse.setText(response);
                    super.onPostExecute(result);
                }
            }
        }


        Layout: 
        <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            tools:context=".MainActivity" >

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:autoLink="web"
                android:text="http://android-er.blogspot.com/"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/info"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
            <TextView
                android:id="@+id/infoip"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

            <ScrollView
                android:layout_width="match_parent"
                android:layout_height="match_parent" >

                <TextView
                    android:id="@+id/msg"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />
            </ScrollView>

        </LinearLayout>

Instead

socket = new Socket(dstAddress, dstPort);

use:

socket = new Socket();
SocketAddress sockaddr = new InetSocketAddress(dstAddress, dstPort);
socket.connect(sockaddr, CONNECT_TIMEOUT_MILLISECONDS);

and it will accept both numeric IP or Hostnames

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM