Repository: pytorch
Issue: DDP Elastic "master_addr" resolution error in environment variables.
Labels: oncall: distributed,triaged,module: elastic

### 🐛 Describe the bug

I found a problem with MASTER_ADDR in DDP.  When dynamic backend(c10d) is used, the obtained MASTER_ADDR is resolved to the machine name. As a result, the connection fails to be obtained from the environment variable during **init_process_group**.
The specific test cases are as follows:
Python script in use **"test_master_addr.py"**:
```python
import os
def main():
    print('RANK = ', int(os.environ['RANK']))
    print('MASTER_ADDR = ', os.environ["MASTER_ADDR"])
    print('MASTER_PORT = ', os.environ["MASTER_PORT"])

if __name__ == "__main__":
    main()
```
Here are three test scenarios:
(1) Using the rendezvous static backend
The startup command is as follows:
```bash
torchrun --nproc_per_node=1 --nnodes=1 test_master_addr.py
```
and the result is:
```bash
RANK =  0
MASTER_ADDR =  127.0.0.1
MASTER_PORT =  29500
```

(2) Using the rendezvous static backend, and specify the master address and port.
The startup command is as follows:
```bash
torchrun --nproc_per_node=1 --nnodes=1 --node_rank=0 --master_addr="51.38.95.133" --master_port=12345 test_master_addr.py
```
and the result is:
```bash
RANK =  0
MASTER_ADDR =  51.38.95.133
MASTER_PORT =  12345
```

(3) Using the rendezvous dynamic backend (c10d), and specify the rdzv_endpoint.
The startup command is as follows:
```bash
torchrun --nproc_per_node=1 --nnodes=1 --rdzv-backend=c10d --rdzv_id=1 --rdzv_endpoint=51.38.95.133:12345 test_master_addr.py
```
and the result is:
```bash
RANK =  0
MASTER_ADDR =  centos7-133
MASTER_PORT =  32905
```

When I fixed this problem, all three test scenarios were able to get MASTER_ADDR correctly from the environment variable.
The modification is as follows:

```python
torch/distributed/elastic/agent/server/api.py:

def _get_fq_hostname() -> str:
    return socket.getfqdn(socket.gethostname())

# add this function 
def _get_fq_host_ip() -> str:
    return socket.gethostbyname(socket.gethostname())

......

@staticmethod
    def _set_master_addr_port(
        store: Store,
        master_addr: Optional[str],
        master_port: Optional[int],
        local_addr: Optional[str],
    ):
        if master_port is None:
            sock = _get_socket_with_port()
            with closing(sock):
                master_port = sock.getsockname()[1]

        if master_addr is None:
            # If user specified the address for the local node, use it as the master addr if not exist
            if local_addr:
                master_addr = local_addr
            else:
                # master_addr = _get_fq_hostname() 
                master_addr = _get_fq_host_ip()   # Use _get_fq_host_ip instead of _get_fq_hostname

        store.set("MASTER_ADDR", master_addr.encode(encoding="UTF-8"))
        store.set("MASTER_PORT", str(master_port).encode(encoding="UTF-8"))
```

Now retest:
```bash
#The result of （1）:
RANK =  0
MASTER_ADDR =  127.0.0.1
MASTER_PORT =  29500

#The result of （2）:
RANK =  0
MASTER_ADDR =  51.38.95.133
MASTER_PORT =  12345

#The result of （3）:
RANK =  0
MASTER_ADDR =  51.38.95.133
MASTER_PORT =  36499
```

### Versions

Collecting environment information...
PyTorch version: 2.1.0a0+git6c0bba3
Is debug build: False
CUDA used to build PyTorch: None
ROCM used to build PyTorch: N/A

OS: CentOS Linux 7 (Core) (x86_64)
GCC version: (GCC) 7.5.0
Clang version: Could not collect
CMake version: version 3.20.5
Libc version: glibc-2.17

Python version: 3.9.17 (main, Jul  5 2023, 20:41:20)  [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-3.10.0-957.el7.x86_64-x86_64-with-glibc2.17
Is CUDA available: False
CUDA runtime version: No CUDA
CUDA_MODULE_LOADING set to: N/A
GPU models and configuration: No CUDA
Nvidia driver version: No CUDA
cuDNN version: No CUDA
HIP runtime version: N/A
MIOpen runtime version: N/A
Is XNNPACK available: True

CPU:
Architecture:          x86_64
CPU op-mode(s):        32-bit, 64-bit
Byte Order:            Little Endian
CPU(s):                96
On-line CPU(s) list:   0-95
Thread(s) per core:    2
Core(s) per socket:    24
Socket(s):             2
NUMA node(s):          2
Vendor ID:             GenuineIntel
CPU family:            6
Model:                 85
Model name:            Intel(R) Xeon(R) Platinum 8260 CPU @ 2.40GHz
Stepping:              7
CPU MHz:               1000.000
CPU max MHz:           2401.0000
CPU min MHz:           1000.0000
BogoMIPS:              4800.00
Virtualization:        VT-x
L1d cache:             32K
L1i cache:             32K
L2 cache:              1024K
L3 cache:              36608K
NUMA node0 CPU(s):     0-23,48-71
NUMA node1 CPU(s):     24-47,72-95
Flags:                 fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf eagerfpu pni pclmulqdq dtes64 ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch epb cat_l3 cdp_l3 intel_pt ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm mpx rdt_a avx512f avx512dq rdseed adx smap clflushopt clwb avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts pku ospke avx512_vnni spec_ctrl intel_stibp flush_l1d arch_capabilities

Versions of relevant libraries:
[pip3] numpy==1.25.2
[pip3] torch==2.1.0a0+git6c0bba3
[conda] numpy                     1.25.2                   pypi_0    pypi
[conda] torch                     2.1.0a0+git6c0bba3          pypi_0    pypi

cc @mrshenli @pritamdamania87 @zhaojuanmao @satgera @rohan-varma @gqchen @aazzolini @osalpekar @jiayisuse @H-Huang @kwen2501 @awgu @penguinwu @dzhulgakov